4

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']
mdatsev
  • 3,054
  • 13
  • 28

3 Answers3

5

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);
mdatsev
  • 3,054
  • 13
  • 28
4

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

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}`);
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405