最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Count the number of trues in a JavaScript object - Stack Overflow

programmeradmin5浏览0评论

Say I have the following object:

  items = {
    1: true,
    2: false,
    3: true,
    4: true
  },

How would I count the number of trues? So a simple function that would return the number 3 in this case.

Say I have the following object:

  items = {
    1: true,
    2: false,
    3: true,
    4: true
  },

How would I count the number of trues? So a simple function that would return the number 3 in this case.

Share Improve this question edited Mar 13, 2021 at 12:59 halfer 20.4k19 gold badges108 silver badges201 bronze badges asked Oct 17, 2018 at 3:17 cup_ofcup_of 6,69710 gold badges51 silver badges104 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 11

You can reduce the object's values, coercing trues to 1 and adding them to the accumulator:

const items = {
  1: true,
  2: false,
  3: true,
  4: true
};

console.log(
  Object.values(items).reduce((a, item) => a + item, 0)
);

That's assuming the object only contains trues and falses, otherwise you'll have to explicitly test for true:

const items = {
  1: true,
  2: false,
  3: 'foobar',
  4: true
};

console.log(
  Object.values(items).reduce((a, item) => a + (item === true ? 1 : 0), 0)
);

const items = {
  a: false,
  b: true,
  c: false,
  d: false,
  e: false
};

const count = Object.values(items).filter(item => item === true).length;

console.log(count);//1

var items = {
    1: true,
    2: false,
    3: true,
    4: true
};

function countTrue4obj(obj) {
    var count = 0;
    for (var p in obj) {
        if (obj.hasOwnProperty(p) && obj[p] === true) {
            count++
        }
    }
    return count;
}

console.log(countTrue4obj(items));

You might consider using a Set. Rather than storing true and false, simply add or delete.

const items = new Set();

items.add(1)
items.add(3)
items.add(4)

// 3
console.log(items.size)
发布评论

评论列表(0)

  1. 暂无评论