Merge multiple arrays based on their index using javascript
You could use Array#reduce
and Array#map
for an arbitrary count of arrays with same length.
var a1 = [1, 2, 3, 4],
a2 = ["a", "b", "c", "d"],
a3 = [9, 8, 7, 6],
a4 = ["z", "y", "x", "w"],
result = [a1, a2, a3, a4].reduce((a, b) => a.map((v, i) => v + b[i]));
console.log(result);
ES5
var a1 = [1, 2, 3, 4],
a2 = ["a", "b", "c", "d"],
a3 = [9, 8, 7, 6],
a4 = ["z", "y", "x", "w"],
result = [a1, a2, a3, a4].reduce(function (a, b) {
return a.map(function (v, i) {
return v + b[i];
});
});
console.log(result);
You can use Array#map
in plain javascript.
var array1 = [1, 2, 3, 4];
var array2 = ["a", "b", "c", "d"];
var newArray = array1.map((e, i) => e + array2[i]);
console.log(newArray);
If you use map on array1 then first parameter is current value of array1 in loop and the second parameter is index of that element in array. So you can match current element in array1 with elements from other arrays with the same index using index.
var array1 = [1, 2, 3, 4];
var array2 = ["a", "b", "c", "d"];
var array3 = ["f", "d", "s", "a"];
var newArray = array1.map(function(value, index) {
return value + array2[index] + array3[index];
});
console.log(newArray);