Two dimensional Array insert an column Javascript

Viewed 1599

I have an question, I want to add an column to all my rows in a two dimensional array.For example:

var arr = [["Tom",456],["Peter",756],["Sara",348]];

var arr_1 = ["USA","GERMANY",AUSTRIA"];

Match this array to:

[["Tom",456,"USA"],["Peter",756,"GERMANY"],["Sara",348,"AUSTRIA"]];

Do you have an solution with an loop or an match function?

4 Answers

Try this:

const mapToNewArray = (arr, arrTwo) => {
    return arr.map((elem, index) => { elem.push(arrTwo[index]); return elem; });
}

let newArray = mapToNewArray(arr, arr_1);

Pass both of the arrays to the function. Run a .map() on the first array and track the index. Pick the corresponding element from the second array (based on index) and push it to the first array's current element.

You can do something like that:


function addColumn(array, column) {

for (let i = 0; i < array.length; i++) {
  // extra check if corresponding item is present in column by index
  if (column[i]) {
   array[i].push(column[i]);
  }
}

return array;

}

var arr = [["Tom",456],["Peter",756],["Sara",348]];
var arr_1 = ["USA","GERMANY","AUSTRIA"];

addColumn(arr, arr_1);

arr.forEach((item, index) => item.push(arr_1[index]));
console.log(arr);

If count of elements in both the arrays are same and doesn't matter it fills undefined holes when lengths are not equal.

To avoid undefined in array, add check before pushing.

Related