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;
}
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With