如何计算数组中符合条件的所有对象?

时间:2017-12-21 10:46:28

标签: javascript arrays function

如何计算数组中符合条件的所有对象:is_read == true

这就是我的数组的样子:

[
  {
    "id": 1,
    "is_read": true,
  },
  {
    "id": 2,
    "is_read": true,
  },
  {
    "id": 3,
    "is_read": false,
  },
  {
    "id": 4,
    "is_read": true,
  },
]

5 个答案:

答案 0 :(得分:3)

通过传递filter函数并使用callback属性应用于过滤结果,只需使用length方法。



let data = [ { "id": 1, "is_read": true, }, { "id": 2, "is_read": true, }, { "id": 3, "is_read": false, }, { "id": 4, "is_read": true, }, ],
length = data.filter(function(item){
  return item.is_read;
}).length;
console.log(length);




您还可以使用lambda表达式。



 let data = [ { "id": 1, "is_read": true, }, { "id": 2, "is_read": true, }, { "id": 3, "is_read": false, }, { "id": 4, "is_read": true, }, ],
length = data.filter(d=>d.is_read).length;
console.log(length);




答案 1 :(得分:3)

过滤

const count = (arr, condition) => arr.filter(condition).length;

const arr = [ { is_read: true }, { is_read: false} ]
console.log(count(arr, (o) => o.is_read));

<强>阵列#减少

const count = (arr, condition) => arr.reduce((acc, c) => condition(c) ? ++acc : acc, 0);

const arr = [ { is_read: true }, { is_read: false } ]
console.log(count(arr, (o) => o.is_read));

<强>递归

const count = ([first, ...rest], condition, acc = 0) => 
           (condition(first) && ++acc, 
           rest.length ? count(rest, condition, acc) : acc);

const arr = [ { is_read: true }, { is_read: false } ]
console.log(count(arr, (o) => o.is_read));

答案 2 :(得分:2)

使用数组filter方法。

//ES6
const arr = [
  {
    "id": 1,
    "is_read": true,
  },
  {
    "id": 2,
    "is_read": true,
  },
  {
    "id": 3,
    "is_read": false,
  },
  {
    "id": 4,
    "is_read": true,
  },
]

const size = arr.filter(obj => obj.is_read).length

答案 3 :(得分:2)

使用Array.reduce

const r = (sum, obj) => sum + (obj.is_read == true ? 1 : 0);
const count = arr.reduce(r, 0);

console.log(count);

答案 4 :(得分:0)

您可以使用 Array#reduce,从 0 开始并为每个元素添加谓词的结果。这是有效的,因为可以将 true 强制转换为 1 并将 false 强制转换为 0

const getMatchCount = (arr, predicate)=>arr.reduce((a,b)=>a + predicate(b), 0);

console.log(getMatchCount([{ "id": 1, "is_read": true, }, { "id": 2, "is_read": true, }, { "id": 3, "is_read": false, }, { "id": 4, "is_read": true, }], 
  x => x.is_read));
// get number of objects in the array whose "is_read" property is true

console.log(getMatchCount([1, 2, 3, 6, 13, -2, 9, 9], 
  x => x % 2 === 1));
// get number of odd numbers in array