0

I have this small code snippet:

let data = [1, 2];
let newBody = {};

let newArray = data.reduce((acc, current) => {
  newBody.doc = current;
  acc.push(newBody);
  return acc;
}, []);

The result is:

newArray = [ { doc: 2 }, { doc: 2 } ]

If I'm redeclaring the empty newBody inside the iteration, its working fine. But if I declare it outside its getting the value of the last array element and applying it to all the other elements and I'm not sure why.

3
  • 1
    You're using the same object reference over and over, modifying the one object, and pushing multiple references to the same object into an array. If I'm redeclaring the empty newBody inside the iteration, its working fine. <-- that's the answer. Commented May 13, 2020 at 0:36
  • 1
    Also, this is rather a job for .map() as opposed to .reduce(). What your code does is equivalent to this: jsfiddle.net/khrismuc/82ezLu3o Commented May 13, 2020 at 0:38
  • @MarkMeyer Yeah, As one of the comment said its because of closures, so I guess I have to look into closures more indepth. ChrisG - This is a simplified version of what I'm doing inside the reduce so that's why it looks like I should've used .map Commented May 13, 2020 at 1:03

1 Answer 1

1

You are using a closure on accident. Put the newBody in it's proper scope:

let data = [1, 2];

let newArray = data.reduce((acc, current) => {
  let newBody = {};
  newBody.doc = current;
  acc.push(newBody);
  return acc;
}, []);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.