I have an array of objects which roughly look like this:
var arr = [{id: 1, name:"Sam", loc: "A"}, {id: 2, name:"Sam", loc: "A"}, {id: 3, name:"fam",loc: "C"}];
From this I want to get another array like this (an array of objects containing name and location of 'Sam' ):
[
{
"name": "Sam",
"loc": "A"
},
{
"name": "Sam",
"loc": "A"
}
]
var res = arr.reduce((a, {name, loc})=>{
name === "Sam" ? [...a, {name, loc}] : a ;
}, []);
But I'm getting an error:
Uncaught Type-error: a is not iterable
What am I doing wrong?
filterwould be a dramatically better choice thanreducethere.const res = arr.filter(({name}) => name === "Sam");Unless you're doing FP (functional programming) and passing a pre-existing function intoreduce, there are almost always better alternatives thanreduce, usually a simple loop.filter+map. Like some others, my view is thatreduceis almost never the right tool.reduceperform better thanfilter+map, say, in this case because of two loops in the later? Also, I don't have a data to prove, but I have observed the answers written withreducetend to get higher upvotes here on SO. :p