I am new to JavaScript. I am little confused even after reading multiple answers and Mozilla.org docs... My issue is that if there's a simple array I am able to use .map,.filter easily but if array has objects then it becomes a little confusing.
E.g. - I have to add all ages here.
I know .map might not work as it gives a new array (which I don't want here), .filter won't work (that's for returning elements that satisfy given condition), forEach don't returns anything.
I am not allowed to use for loop but that's the most convenient here (Below code is correct & working).
How else can I solve it?
const users=[
{firstName:"john",lastName:"Biden",age:26},
{firstName:"jimmy",lastName:"cob",age:75},
{firstName:"sam",lastName:"lewis",age:50},
{firstName:"Ronald",lastName:"Mathew",age:26},
];
var total=0
//console.log(users.length)
for(let i=0;i<users.length;i++){
//console.log(users[i].age)
total+=users[i].age
}
console.log(total)
You can use forEach where you use the for
You can use map to make an array of ages and reduce it to sum it
You can use filter to count only those above or equal to 50 years of age
The ({age})
is using destructuring to get a just the age of the object array as an alternative to total=users.map(item => { return item.age })
const users=[
{firstName:"john",lastName:"Biden",age:26},
{firstName:"jimmy",lastName:"cob",age:75},
{firstName:"sam",lastName:"lewis",age:50},
{firstName:"Ronald",lastName:"Mathew",age:26},
];
// forEach needs the total initialised
let total=0
users.forEach(user => total+=user.age)
console.log(total)
// map plus reduce (to sum) does not need to initialise
total=users.map(({age}) => age)
.reduce((a,b) => a+b)
console.log(total)
// filter plus reduce also does not need initialising the total
let total50Plus=users.filter(({age}) => age>=50)
.reduce((a,b) => a.age+b.age) // does not need an accumulator initialised
console.log(total50Plus)
// the standard reduce initialises the accumulator at the end of the function
total=users.reduce((acc,{age}) => acc+=age,0);
console.log(total)
// full version
total=users.reduce((accumulator, current) => {
accumulator += current.age;
return accumulator;
},0); // initialise the accumulator
console.log(total)