Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate the count of object using reduce or filter in javascript

I've written a method to calculate the number of objects in an array which have 'enabled' set to 'true'.

I'm adding 1 to counter each time it finds an object in my array which has 'enabled' set to 'true'.

How could I achieve this without using 'counter' variable and using reduce or filter instead??

Here's my code:

function getCount() {               
    const arr =[[{ "enabled": true }], [{ "enabled": false}, {"enabled": true}]];                       
    var count = 0;
    arr.forEach(function(ar){
        ar.forEach(function(obj){
            if(obj.enabled) {
                count++;
            }
        })
    });
    return count;           
}
like image 719
Sunny Avatar asked Sep 15 '25 16:09

Sunny


2 Answers

Have a look below, I've added a comment:

[].concat(...arr) /* flatten the array */
.filter(item => item.enabled) /* return only enabled: true */
.length /* get the count */

const arr = [
  [{
    "enabled": true
  }],
  [{
    "enabled": false
  }, {
    "enabled": true
  }]
];
var enabledCount = [].concat(...arr).filter(item => item.enabled).length
console.log(enabledCount)

Or you can use reduce, if you want

const arr = [
  [{
    "enabled": true
  }],
  [{
    "enabled": false
  }, {
    "enabled": true
  }]
];

var enabledCount = arr.reduce(
  (accumulator, currentValue) => accumulator.concat(currentValue), []
).filter(item => item.enabled).length

console.log(enabledCount)
like image 180
StudioTime Avatar answered Sep 18 '25 08:09

StudioTime


Using a helper reduce function gives the simplest implementation in my opinion:

const arr =[
 [
     {"enabled": true},
     {"enabled": true}
 ],
 [
     {"enabled": false}, 
     {"enabled": true},
     {"enabled": true}
 ]
]; 

// Helper function to count inner arrays
const r = (i) => i.reduce( (p, c) => c.enabled ? p = p + 1 : p, 0)

const count = arr.reduce( (p, c) => p + r(c), 0) // Output: 4
like image 23
Attaque Avatar answered Sep 18 '25 10:09

Attaque