-1

my function has to take 2 arrays and if one of the arrays is shorter than the other it needs to fill in the blanks with nulls.

so i could do this easier now that i think about it but i would really like to know what i have missed.

the specific part of my code is the nested forEach loops i cant understand that when i invoke my function like this

fillSquare([1,2,3],[1,2,3,4,5])

I get [[1,2,3,4,5],[1,2,3,4,5]] instead of [[1,2,3,null,null][1,2,3,4,5]]

const fillSquare = arr => {
  const maxArrayLength = Math.max(
    ...arr.map(arr => {
      return arr.length;
    })
  );



  let arrayMatrix = new Array(arr.length).fill(
    new Array(maxArrayLength).fill(null)
  );

  arr.forEach((arry, mainIndex) => {
    arry.forEach((item, subIndex) => {
      console.log(mainIndex, "<--main", "sub-->", subIndex, "=", item);
      arrayMatrix[mainIndex][subIndex] = item;
    });
  });
  console.log(arrayMatrix);
  return arrayMatrix;
};

Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

1

When debugging, it seems:

let arrayMatrix = new Array(arr.length).fill(
   new Array(maxArrayLength).fill(null)
);

// arrayMatrix[1] == arrayMatrix[0] => true

is only creating 1 array instance. setting 1 value on one sets it on both.

heres how to fix your issue

let arrayMatrix = new Array(arr.length).fill(0).map( _ => new Array(maxArrayLength).fill(null));

this is my version - now immutable

function fillSquare(arr) {
    let clone = [...arr]
    let maxDepth = arr.reduce( (c, subarr) => c = Math.max(c, subarr.length), 0)
    clone.forEach((subarr, index) => {
        let len = clone[index].length;
        clone[index].length = maxDepth;
        clone[index].fill(null, len, maxDepth);
    })
    return clone;
}

the import notes are you can set the length and fill the gaps. Also check out reduce if you need.

Jacob Thomas
  • 240
  • 1
  • 13
-2

const fillSquare = function(arr){
  let minLengthArr = arr[0];
  let maxLength = arr[1].length;
  
  if(arr[1].length < arr[0].length){    
    minLengthArr= arr[1];
    maxLength = arr[0].length;
  }
  
  let itemsToPush = maxLength - minLengthArr.length;
  for(let i=0;i<itemsToPush;i++){
    minLengthArr.push(null);
 }
  return arr;  
}

var r = fillSquare([[1,2,3],[1,2,3,4,5]]);
console.log(r);
Vishnu
  • 897
  • 6
  • 13