按属性值计算数组中的项目

时间:2017-05-23 11:57:35

标签: javascript jquery

我有这个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实现它?

5 个答案:

答案 0 :(得分:2)

您可以使用Array#reduce进行检查并添加比较值。

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/progress">
    <scale android:scaleWidth="100%">
        <shape>
            <corners android:radius="5dip"/>
            <solid android:color="#33FF33"/>
        </shape>
    </scale>
</item>

答案 1 :(得分:1)

max-width:100%

答案 2 :(得分:1)

试试这段代码,

&#13;
&#13;
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 = 0;
arr1.forEach(function(e) {
  if (e.type == 1 || e.type == 3 ) 
   {
       count++;
   }
 });

alert(count);
&#13;
&#13;
&#13;

将在变量&#34; count&#34;

中获取属性类型1和3的计数

答案 3 :(得分:1)

您可以调用以下函数:

function count(arr) {   
  return $.grep(arr, function( n ) {
     return ( (n.type === 1) || (n.type === 3) );
  }).length;
}

使用您的数组:

count(arr1);

答案 4 :(得分:1)

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;