0

When I run the following code, the console logs give me exactly what I want, but the end array of objects doesn't which I really don't understand..

function pickWinners(numbers) {  
    const winnerArr = [];
    const winnerObj = {};
    for(let i = 0; i < numbers.length; i++) {
        if(numbers[i] % 2 != 0 && i % 2 != 0) {
            winnerObj.seat = i;
            winnerObj.ticketCost = numbers[i];
            console.log(winnerObj);
            winnerArr.push(winnerObj);
        }
    }
    return winnerArr;
}

pickWinners([6, 7, 12, 49])

The console log gives me (as expected):

Object { seat: 1, ticketCost: 7 }   
Object { seat: 3, ticketCost: 49 }

But the returned array is:

0: Object { seat: 3, ticketCost: 49 }  
1: Object { seat: 3, ticketCost: 49 }

Could someone please explain what is going on? Especially when the console log is executed just before the push.

Thanks in advance!

I was expecting the returned array to be the same result as what was printed with the console log

Carson
  • 2,700
  • 11
  • 24
Calor1
  • 9
  • 3
  • 1
    You're pushing the same object over and over again. You'll have to re-initialize `winnerObj` **inside** the loop. – Pointy Jan 15 '23 at 22:44
  • place the `const winnerObj = {};` inside your loop, otherwise it's just the same instance. – Keith Jan 15 '23 at 22:44

1 Answers1

1

You need to define your winnerObj inside your for loop so it is block-scoped. This causes a new winnerObj to be created each time. The code you currently have is using the same winnerObj for each instance. And when you change winnerObj, it changes the instances that are already in the array, too.

If you still don't understand, try reading this: https://dmitripavlutin.com/value-vs-reference-javascript/

function pickWinners(numbers) {
  const winnerArr = [];
  for(let i = 0; i < numbers.length; i++) {
    const winnerObj = {};
    if(numbers[i] % 2 != 0 && i % 2 != 0) {
      winnerObj.seat = i;
      winnerObj.ticketCost = numbers[i];
      console.log(winnerObj);
      winnerArr.push(winnerObj);
    }
  }
  return winnerArr;
}

console.log("overall:", pickWinners([6, 7, 12, 49]))
Richard Henage
  • 1,758
  • 1
  • 3
  • 10