简体   繁体   中英

Two dimensional Array insert an column Javascript

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?

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);

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.

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.

There are many ways to loop through an array in JavaScript: https://www.codespot.org/ways-to-loop-through-an-array-in-javascript/

Maybe the easiest to understand way to do this is:

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

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

for (let i = 0; i < arr.length; i++) { 
    arr[i].push(arr_1[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM