2

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?

2
  • Use a loop and push() to append the element of one array to the nested arrays in the other. Commented May 6, 2021 at 16:27
  • do you want a new array or keeping the given one with given arrays? Commented May 6, 2021 at 16:29

4 Answers 4

2
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.