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;
}
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;
}
Share
Improve this question
edited Oct 31, 2018 at 13:08
Sunny
asked Oct 31, 2018 at 12:49
SunnySunny
9324 gold badges20 silver badges44 bronze badges
2
|
4 Answers
Reset to default 9Have 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
Would something like this work?
const arr =[[{ "enabled": true }], [{ "enabled": false}, {"enabled": true}]];
const enabledArray = arr.map(function(item) {
return item.filter(function(subItem){
return subItem.enabled === true;
})
})
const enabledItems = enabledArray.length;
You could do:
const arr = [[{ "enabled": true }], [{ "enabled": false }, { "enabled": true }]];
console.log(
arr.reduce(
// Flatten the array of arrays
(acc, curVal) => acc.concat(curVal), []
).filter(
// Filter so you have an array with
// objects that have 'enable': true
(obj) => Object.is(obj['enabled'], true))
// and then return the length of it
.length
);
obj.seatMapAvailable
? Did you meanobj.enabled
? – StudioTime Commented Oct 31, 2018 at 13:00