Alexander Kundurdjiev
Alexander Kundurdjiev

Reputation: 85

Fill array in two dimensional array at a specific index using JavaScript

I want to fill inner array of two dimensional array with items at specific index. The problem in this case is that every inner array is filled with that items.

Try: link_to_code_img

Result: link_to_result_img

the code:

Array.prototype.repeat= function(what, L){
  while(L) this[--L]= what;
  return this;
};

var yearsdays = [].repeat([], 365);

for(var i = 0; i<= yearsdays.length; i++){
   if(i === 99) {
      yearsdays[i].push(99)
   }
}

the result:

Array[365]
  [0 … 99]
     0: Array[1]
       0: 99
       length: 1
       __proto__: Array[0]

     1: Array[1]
       0: 99
       length: 1
       __proto__: Array[0]

     2: Array[1]
       0: 99
       length: 1
       __proto__: Array[0]

     and etc.......

The problem is that as a result every array in yearsdays was filled with number 99, but not only array with index 99 as I expect. What am I doing wrong?

Upvotes: 2

Views: 227

Answers (3)

Redu
Redu

Reputation: 26161

In order to generate a proper 2D array all nested array items should be unique. Due to objects being reference types in JS you have to be ceraful when generating multi-dimensional arrays in JS. One possible and generic way of creating a multi-dimensional array is;

Array.prototype.clone = function(){
  return this.reduce((p,c,i) => (p[i] = Array.isArray(c) ? c.clone() : c, p),[])
}

function arrayND(...n){
  return n.reduceRight((p,c) => c = (new Array(c)).fill(true).map(e => Array.isArray(p) ? p.clone() : p ));
}

yearsdays = arrayND(365,1,0);
yearsdays[6][0]="Sunday";
console.log(yearsdays);

Upvotes: 0

Charlie
Charlie

Reputation: 23778

You pass the same array to the repeat function. So it is going to be 365 references to a single array.

A correct way to do this is:

Array.prototype.repeat= function(L){
      while(L) this[--L]= new Array();
      return this;
};

Upvotes: 0

sertsedat
sertsedat

Reputation: 3600

As Redu stated in the comments

Your inner arrays are all references of each other

You can get away from this problem like this. It somehow clones the array so the references are different.

Array.prototype.repeat= function(what, L){
  while(L) this[--L]= what.slice(0); // <--- Here
  return this;
};

Upvotes: 2

Related Questions