按属性值计算数组中的项

xqnpmsa8  于 2022-09-21  发布在  jQuery
关注(0)|答案(2)|浏览(201)

我有这个Java脚本数组:

var arr1 = [{id:'124',name:'qqq',type=3}, 
            {id:'589',name:'www',type=1}, 
            {id:'45',name:'eee',type=1},
            {id:'567',name:'rrr',type=1},
            {id:'124',name:'qqq',type=2}, 
            {id:'589',name:'ddd',type=2}, 
            {id:'45',name:'qqq',type=1},
            {id:'567',name:'vvv',type=3}]

我需要计算arr1数组中具有类型属性1或3的项。

我如何使用jQuery实现它?

zaq34kh6

zaq34kh61#

var arr1 = [{id:'124',name:'qqq',type=3}, 
            {id:'589',name:'www',type=1}, 
            {id:'45',name:'eee',type=1},
            {id:'567',name:'rrr',type=1},
            {id:'124',name:'qqq',type=2}, 
            {id:'589',name:'ddd',type=2}, 
            {id:'45',name:'qqq',type=1},
            {id:'567',name:'vvv',type=3}];

var count = arr.filter(item => item.type === 3 || item.type === 1).length;
r7xajy2e

r7xajy2e2#

您可以使用带有复选标记的Array#reduce并添加比较的值。

var array = [{ id: '124', name: 'qqq', type: 3 }, { id: '589', name: 'www', type: 1 }, { id: '45', name: 'eee', type: 1 }, { id: '567', name: 'rrr', type: 1 }, { id: '124', name: 'qqq', type: 2 }, { id: '589', name: 'ddd', type: 2 }, { id: '45', name: 'qqq', type: 1 }, { id: '567', name: 'vvv', type: 3 }],
    count = array.reduce(function (r, a) {
        return r + +(a.type === 1 || a.type === 3);
    }, 0);

console.log(count);

相关问题