const users=[
{name: "Julia", age: 20},
{name: "Jane", age: 30}
];
How can we do that we find summary of ages with reduce() function or others?
const users=[
{name: "Julia", age: 20},
{name: "Jane", age: 30}
];
How can we do that we find summary of ages with reduce() function or others?
You can set accumulator to 0
and in each iteration add the age
property of the element to ac
and return it.
const users=[
{name: "Julia", age: 20},
{name: "Jane", age: 30}
];
const sum = users.reduce((ac,a) => ac + a.age,0);
console.log(sum);
Using simple loops it will look like.
const users=[
{name: "Julia", age: 20},
{name: "Jane", age: 30}
];
let sum = 0;
for(let i = 0;i<users.length;i++){
sum += users[i].age
}
console.log(sum)
Sum the value with the accumulator, where as initial value of accumulator is 0
The 0
at the end is the initial value of the accumulator.acc += curr.age
will add the age of the each object with accumulator value
const users = [{
name: "Julia",
age: 20
},
{
name: "Jane",
age: 30
}
];
let k = users.reduce((acc, curr) => acc += curr.age, 0);
console.log(k)