0
const allocation = [
   {partner: 3},
   {partner: 1},
   {partner: 2},
   {partner: 0},
   {partner: 4}
];

const rightallocation = new Array(5);
rightallocation.fill({number: 1});

for (let i = 0; i < allocation.length; i++) {

   const rightIndex = allocation[i].partner;
   rightallocation[rightIndex].number = i;


   console.log("Filling "+ (i) + " into rightallocation["+ (allocation[i].partner)+"]");
   console.log(rightallocation[allocation[i].partner]);
}

console.log(rightallocation); 

This code should take the array 'allocation' and mirror it. e.g. allocation[0] = 3, so rightallocation[3]= 0. All my logs inside the for give the correct numbers, but i get an array that is full of number:4 (last index)

here is the console log

1 Answers1

3

It's because the same object is being referenced 5 times in your rightallocation array.

So this line:

rightallocation[rightIndex].number = i;

Is changing .number for all elements in your array every time, because all elements are a reference to just the single {number : 1} object that you filled your rightallocation array with when you did this:

rightallocation.fill({number: 1})

Try changing these lines:

const rightallocation = new Array(5);
rightallocation.fill({number: 1});

To something like this:

const rightallocation = new Array(5).fill().map(u => ({number: 1}));

To make it clearer what happened, try filling your array with something more explicit like this. This will make sure that a new object is always created and you end up with five different objects in your array:

const rightallocation = [];

for (let i=0; i < 5; i++) {
  rightallocation.push({number: 1});
}
heymoo
  • 81
  • 1
  • 3