knitty
knitty

Reputation: 57

How to merge two arrays into one? Retain array elements and length

I have two arrays in my project right now, I am looking to merge or join them so I can have the result output to a table.

var array1 = ["a","b"];
var array2 = ["x", "y"];

I know there are methods like concat and push, but I can't seem to find a method for exactly what I'm trying to do, because concat just adds to the array.

My expected output is

var combinedarray = ["x and a","y and b"];

Upvotes: 0

Views: 179

Answers (4)

Shidersz
Shidersz

Reputation: 17190

Here is one approach using reduce() over the array2:

var array1 = ["a","b"];
var array2 = ["x", "y", "z"];

let res = array2.reduce(
    (acc, e, i) => acc.push(e + " and " + (array1[i] || "?")) && acc,
    []
);

console.log(res);

Also, this can be shortened a little using the spread operator:

var array1 = ["a","b"];
var array2 = ["x", "y", "z"];

let res = array2.reduce((acc, e, i) => [...acc, e + " and " + (array1[i] || "?")], []);

console.log(res);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386530

You could get the transposed array and join the elements later for getting a readable string.

var array1 = ["a","b"],
    array2 = ["x", "y"],
    result = [array1, array2]
        .reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), [])
        .map(a => a.concat(a.splice(-2, 2).join(' and ')).join(', '))

console.log(result);

An example with three arrays.

var array1 = ["a","b"],
    array2 = ["x", "y"],
    array3 = ["1", "2"],
    result = [array1, array2, array3]
        .reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), [])
        .map(a => a.concat(a.splice(-2, 2).join(' and ')).join(', '))

console.log(result);

Upvotes: 0

AndrewL64
AndrewL64

Reputation: 16301

You can use a simple for loop like this:

var array1 = ["a","b"];
var array2 = ["x", "y"];
var combinedarray = [];

for (i=0; i < array1.length; i++) {
  combinedarray.push(array1[i] + " and " + array2[i]);  
}

console.log(combinedarray);


Using the map() method as shown by @trincot would be a more concise and cleaner way of doing it though.

Upvotes: 3

trincot
trincot

Reputation: 349999

You can use map with the extra index argument of the callback function, so you can get the corresponding value from the second array:

var array1 = ["a","b"];
var array2 = ["x", "y"];
var result = array1.map((a,i) => `${a} and ${array2[i]}`);
console.log(result);

Upvotes: 5

Related Questions