How to combine two arrays as a cartesian product?
You can use Array.prototype.forEach()
for the iteration over the arrays.
The
forEach()
method executes a provided function once per array element.
var array1 = [1, 2, 3, 4, 5],
array2 = ["one", "two", "three", "four", "five"],
result = [];
array1.forEach(function (a) {
array2.forEach(function (b) {
result.push(b + ' ' + a);
});
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
You can use two for-loops:
var array1 = [1,2,3,4,5];
var array2 = ["one","two","three","four","five"];
var array3 = [];
for (var i = 0; i < array1.length; i++) {
for (var j = 0; j < array2.length; j++) {
array3.push(array2[j] + ' ' + array1[i]);
}
}
console.log(array3);
Yet another way with reduce and map and concat
Snippet based on @Nina Scholz
var array1 = [1, 2, 3, 4, 5],
array2 = ["one", "two", "three", "four", "five"];
var result = array1.reduce(function (acc, cur) {
return acc.concat(array2.map(function (name) {
return name + ' ' + cur;
}));
},[]);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');