0

Why is it when you push a constantly updating object into an array using a for loop, it pushes only the last iteration property values(last updated property values)?

My task was: It is your job to identify every element in an array that isn't sequential.

You should return the results as an array of objects with two values.

I tried this and it didn't work as I expected:

function allNonConsecutive(arr) {
  let nonC = {
    i: 0,
    n: 0,
  };
  let arrNonC = [];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] - 1 !== arr[i - 1]) {
      nonC.i = arr.indexOf(arr[i]);
      nonC.n = arr[i];
      arrNonC.push(nonC);
    } else continue;
  }
  return arrNonC;
}
Returns: [{i:7, n:10}, {i:7, n:10}] ❌ 

Although I solved it like this:

function allNonConsecutive(arr) {
  let nonC = {};
  let arrNonC = [];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] - 1 !== arr[i - 1]) {
      nonC = {
        i: arr.indexOf(arr[i]),
        n: arr[i],
      };
      arrNonC.push(nonC);
    } else continue;
  }
  return arrNonC;
}
Returns: [{i:4, n:6}, {i:7, n:10}] ✔️
Spect
  • 23
  • 8
  • Does this answer your question? [Javascript array with for loop, returns only last element](https://stackoverflow.com/questions/41675574/javascript-array-with-for-loop-returns-only-last-element) – Ivar Mar 18 '23 at 17:02

1 Answers1

1

When you .push() an object, that does not make a copy. Your working version solves that problem by creating a new object on each iteration of the loop. Your original code pushed the same object over and over again, so the array was filled with duplicate references to that object.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • I had problems getting the code here too, thank you for your answer, it makes sense, but not 100% for me, it pushes the same object yes at first, but the object is mutating in that for loop, first the object is with the values of properties i:4, n:6 AND then it moves to i:7, i:10. I mean at 1 point in time the object is{ x } and it pushes x to the array, and at the next point in time it is y and it pushes { y } to the array, that's how I think of it. – Spect Mar 18 '23 at 17:05
  • 2
    @Spect You only ever create one object in your script, which happens outside of the loop. See [Why does changing an Array in JavaScript affect copies of the array?](https://stackoverflow.com/questions/6612385/why-does-changing-an-array-in-javascript-affect-copies-of-the-array) – Ivar Mar 18 '23 at 17:08
  • I understood the concept now, ty guys. – Spect Mar 18 '23 at 17:18