1

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?

6
  • 1
    filter would be a dramatically better choice than reduce there. const res = arr.filter(({name}) => name === "Sam"); Unless you're doing FP (functional programming) and passing a pre-existing function into reduce, there are almost always better alternatives than reduce, usually a simple loop. Commented Jun 18, 2020 at 7:54
  • @T.J.Crowder may be they want the array of objects without 'id'? Commented Jun 18, 2020 at 8:04
  • @ABGR - The data show has only the properties being used. If there were more and they were excerpting them, I'd use a loop first or filter+map. Like some others, my view is that reduce is almost never the right tool. Commented Jun 18, 2020 at 8:50
  • @T.J.Crowder haha the threads are hilarious. But can reduce perform better than filter+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 with reduce tend to get higher upvotes here on SO. :p Commented Jun 18, 2020 at 9:12
  • @ABGR - One pass can be better than two, yes, which is why I'd use a simple loop if I were dealing with hundreds of thousands of array elements. Voting patterns are weird. :-) People do tend to upvote things that seem cool. But being cool isn't what development is about (to me). Being clear is more important (to me). :-) Commented Jun 18, 2020 at 9:25

1 Answer 1

1

You're just missing return in the callback of your reduce. Try this:

var arr = [{id: 1, name:"Sam", loc: "A"}, {id: 2, name:"Sam", loc: "A"}, {id: 3, name:"fam",loc: "C"}];

var res = arr.reduce((a, {name, loc})=>{
   return name === "Sam" ? [...a, {name, loc}] : a ;
}, []);
console.log(res);

Sign up to request clarification or add additional context in comments.

2 Comments

This is an often repeated duplicate of this question.
@T.J.Crowder yup okay

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.