How to combine two arrays as a cartesian product?

不想你离开。 提交于 2019-12-07 05:23:59

问题


I have

array1 = [1,2,3,4,5];
array2 = ["one","two","three","four","five"];

I want to get array3 where all elements of array1 with first (and others) element of array2 and etc.

For example:

array3 = ["one 1", "two 1", "three 1", "four 1", "five 1", "one 2", "two 2", "three 2", "four 2", "five 2"...]

I understand that I need to use for loop but I don't know how to do it.


回答1:


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);



回答2:


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>');



回答3:


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>');



回答4:


There is still the option with loops:

var array2 = [1,2,3,4,5],
array1 = ["one","two","three","four","five"],
m = [];
for(var a1 in array1){  
  for(var a2 in array2){
      m.push( array1[a1]+ array2[a2] );    
  }
}
console.log(m);



回答5:


You can use this method when array1.length and array2.length are equal.

var array1 = [1, 2, 3, 4, 5];
var array2 = ["one", "two", "three", "four", "five"];
var length = array1.length;
var array3 = new Array(Math.pow(length, 2)).fill(0).map((v, i) => array2[i % length] + ' ' + array1[i / length << 0]);


document.body.textContent = JSON.stringify(array3);



回答6:


Try (JS)

function myFunction(){
            var F = [1, 2, 3, 4,5];
            var S = ["one", "two", "three", "four", "five"];
            var Result = [];

           var k=0;
            for (var i = 0; i < F.length; i++) {
                for (var j = 0; j < S.length; j++) {
                    Result[k++] = S[j] + " " + F[i];
                }
            }

            console.log(Result);
        }


来源:https://stackoverflow.com/questions/34826075/how-to-combine-two-arrays-as-a-cartesian-product

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!