I have a series of data stored in a variable:
let groups = [
{
name: "x",
selected: false,
elements: [
{
name: "xa",
selected: false
},
{
name: "xb",
selected: true
},
{
name: "xc",
selected: true
},
{
name: "xd",
selected: false
}
]
},
{
name: "y",
selected: false,
elements: [
{
name: "ya",
selected: false
},
{
name: "yb",
selected: true
},
{
name: "yc",
selected: true
},
{
name: "yd",
selected: false
}
]
}
];
I am looking to determine the number of items with selected = true
.
I have created this function for that purpose:
function countSelected(groups, counter = 0) {
for (let i = 0; i < groups.length; i++) {
const group = groups[i];
if (group.selected) {
counter++;
}
if (group.elements && group.elements.length) {
group.elements.forEach(item => countSelected([item], counter));
}
}
return counter;
}
However, it consistently displays a result of 0.