What I need is to add in a single statement all the lengths of an array which is a property that is found in all the JSON of a JSON array.
Let's take the following json as an example:
[
{
id: 1,
element: [1, 2, 3]
},
{
id: 2,
element: [5]
},
{
id: 3,
element: []
}
]
The statement should add [1, 2, 3].length + [5].length + [].length
which should give 4. The problem is that I need to do it in a single statement, but I haven't been able to do it, I tried with reduce but it's not clear to me how it works.
const array = [
{
id: 1,
element: [1, 2, 3]
},
{
id: 2,
element: [5]
},
{
id: 3,
element: []
}
];
console.log(array.reduce((accumulator, current, idx) => accumulator + array[idx].element.length));
console.log(array.reduce((accumulator, current) => accumulator + current.element.length));
This would be the solution with
reducer
, as a second parameter you must add the value you want thereducer
.