Javascript - Count array objects that have a value

后端 未结 8 599
情话喂你
情话喂你 2021-01-19 01:52

I\'m getting an array returned to me and I need to count the rows that have a value in them

I\'ve tried to call arr.length but that gives me the total length of the

相关标签:
8条回答
  • 2021-01-19 02:48

    Foreach through the array and check if the id key has a value

    var output = 0;
    var arr = [ { id: '1', '': '' },{ id: '2', '': '' },{ id: '3', '': '' },{ id: '4', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' },{ id: '', '': '' } ]
    
    arr.forEach(e => {
      if (e["id"] != '') {
        output++;
      }
    });
    
    console.log(output);

    0 讨论(0)
  • 2021-01-19 02:53

    if you are a fan of Lodash, you can use countBy (documentation)

    const array = [{id:'1','':''},{id:'2','':''},{id:'3','':''},{id:'4','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''},{id:'','':''}]
    
    // The iterator function `obj => obj.id === ''` returns Boolean value `true` or `false`
    const count = _.countBy(array, obj => obj.id !== '');
    
    // Get the `true` value
    console.log(count.true);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

    One liner fans:

    _.countBy(array, obj => obj.id !== '').true;
    
    0 讨论(0)
提交回复
热议问题