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)
2
Answers
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 tototal=users.map(item => { return item.age })
Using ForEach it will be practical to manipulate your array of objects.
Understand the parameters used in the forEach callback:
In the example below follows the code of what you want using forEach.