Beginner Question: Why is this inner for loop not incrementing in JS?

Not sure if looking at code all day is making me blind, beside my natural ignorance, but I can’t find out why I cannot get the inner look to throw its next item into finalDataset. The intent is to generate a new array with some modifications. Appreciate any help.

const arr1 = [
  ["Header1", "Color", "Size"],
  ["Data1", "Blue", 16],
  ["Data2", "Red", 20],
  ["Data3", "Brown", 5],
]
const arr2 = [
  ["Name", "CorrectedColor", "Style"],
  ["Nike", "Black", "Rock"],
  ["Puma", "Purple", "Country"],
  ["ShingLing", "White", "Romantic"],
]

let finalDataset = [];
for (let a = 1; a < arr1.length; a++) {
  let newRow = arr1[a];
  for (let n = 1; n < arr2.length; n++) {
    newRow[0] = arr2[n][1];
    newRow[1] = arr2[n][2];
    newRow[2] = '-'
    console.log(newRow)
    finalDataset.push(newRow)
  }
}
console.log(finalDataset)

>Solution :

You’re pushing references to the same array into finalDataset, so they all take the same value (and you’re changing arr1 while you’re at it – check with console.log(arr1) after your code completes). You can work around this by making copies of the arrays, e.g. using slice (you could also use e.g. [...newRow]):

const arr1 = [
  ["Header1", "Color", "Size"],
  ["Data1", "Blue", 16],
  ["Data2", "Red", 20],
  ["Data3", "Brown", 5],
]
const arr2 = [
  ["Name", "CorrectedColor", "Style"],
  ["Nike", "Black", "Rock"],
  ["Puma", "Purple", "Country"],
  ["ShingLing", "White", "Romantic"],
]

let finalDataset = [];
for (let a = 1; a < arr1.length; a++) {
  let newRow = arr1[a].slice(0);
  for (let n = 1; n < arr2.length; n++) {
    newRow[0] = arr2[n][1];
    newRow[1] = arr2[n][2];
    newRow[2] = '-'
    finalDataset.push(newRow.slice(0))
  }
}
console.log(finalDataset)

Leave a Reply