-1

I have the following two arrays:

const firstArr = [1, 2, 3, 4]
const secondArr = ['somevalue', 'anothervalue', 'another', 'other']

I would like to get the following output:

const final = [[1, 'somevalue'], [2, 'anothervalue'], [3, 'another'], [4, 'other']]

Where each value of the two arrays is associated with another value and put into an array. So for example, the first value of firstArr should be associated with the first value of secondArr in a sub-array on the final array.

Is there some function in Javascript to do this or am i going to have to do it another way, for example with a loop?

Dev012
  • 273
  • 1
  • 3
  • 11
  • This is called "zipping" arrays/lists/etc together, and once you know that, you can pretty much immediately find the answer. For the "duplicate" flag, there are a _lot_ of answers, but https://stackoverflow.com/a/10284006/740553 is the one you want to look at: it's literally a one-liner in modern JS. – Mike 'Pomax' Kamermans Feb 09 '20 at 17:36
  • Indeed, looking for the JS equivalent of zipping is helping me, thanks! – Dev012 Feb 09 '20 at 17:39

2 Answers2

2

You could reduce to a single array

const firstArr = [1, 2, 3, 4]
const secondArr = ['somevalue', 'anothervalue', 'another', 'other'];
const final = firstArr.reduce((arr, val, i) => (arr.push([val, secondArr[i]]), arr), []);

console.log(final)

Or the old-school way if you like it to be less cryptic:

const firstArr = [1, 2, 3, 4]
const secondArr = ['somevalue', 'anothervalue', 'another', 'other'];
const final = [];

for (let i=0; i<firstArr.length; i++) {
  final.push([firstArr[i], secondArr[i]]);
}

console.log(final)
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
1

I think this is what you want.

const firstArr = [1, 2, 3, 4]
const secondArr = ['somevalue', 'anothervalue', 'another', 'other']
let finalArr = [];

firstArr.forEach((elm, i) => {
  finalArr[i] = [elm, secondArr[i]];
});
console.log(finalArr);
ROOT
  • 11,363
  • 5
  • 30
  • 45