Frantz Augustin
Frantz Augustin

Reputation: 61

How do I zip two arrays into one array of strings containing the values

For instance, if I have two arrays that look like this:

var array1 = ['a','b'];
var array2 = [1, 1];

The output array should be:

var newArray = ['a:1', 'b:1']

Upvotes: 4

Views: 3965

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386520

You could map the value of the iterating array and from the other array the value of the actual index.

var array1 = ['a', 'b'],
    array2 = [1, 1],
    result = array1.map((a, i) => [a, array2[i]].join(':'));

console.log(result);

The same with an arbitrary count of arrays

var array1 = ['a', 'b'],
    array2 = [1, 1],
    result = [array1, array2].reduce((a, b) => a.map((v, i) => v + ':' + b[i]));

console.log(result);

Upvotes: 4

Explosion Pills
Explosion Pills

Reputation: 191729

If you are willing to use lodash you can do this very easily with zipWith. It takes arrays and combines the values grouped by index according to a function you provide:

var newArr = lodash.zipWith(array1, array2, (arr1val, arr2val) => `${arr1val}:${arr2val}`);

Upvotes: 2

mdatsev
mdatsev

Reputation: 3879

You could use map like this:

var array1 = ['a','b'], array2 = [1, 1];
var newArray = array1.map((e, i) => `${e}:${array2[i]}`);

console.log(newArray);

Upvotes: 5

Related Questions