Looking for optimized solution for below program.
ArrayOfObj = [ {name: "XYZ" , age:30}, {name: "ABC" , age:30},{name: "ABC" , age:17},{name: "ABCD" , age:41},{name: "XYZ" , age:30}....... n objects ]
Now , I want to get the name(only) in array from all the objects whose age = 30 . output = ["XYZ", "ABC","XYZ" ........]
Both answers are fine, also you can use array.reduce() and doesn’t need two operations(map & filter)
I would simply use the map function and then eliminate the outlayers using filter function. That would be my strategy.
The simplest way would be to first filter the array then map it. Here is the code:
ArrayOfObj.filter((obj) => obj.age == 30).map((obj) => obj.name)
or
ArrayOfObj.filter(function(obj) { return obj.age == 30}).map(function(obj) { return obj.name})
Emil Moe
Senior Data Engineer
ArrayOfObj.reduce((accumulator, current) => { if (current.age !== 30) { return; } accumulator.push(current.name); return accumulator; }, []);