简体   繁体   中英

Creating a custom array from 2 existing arrays

I have 2 arrays like these,

array_1 = [1,2,3]
array_2 = [a,b] 

i want to get 6 arrays in kurasulst like below results.

[1,a]
[1,b]
[2,a]
[2,b]
[3,a]
[3,b]

i have tried but not successfull.

var rowCount = array_1.length + array_2.length; 
console.info("rowCount",rowCount);
var array_1Repeat = rowCount/(array_1.length);
var array_2Repeat = rowCount/(array_2.length);
console.info("array_1Repeat",array_1Repeat);
console.info("array_2Repeat",array_2Repeat);

var kurasulst =[];
for(var i=0; i<rowCount.length; i++){
    console.info("array_1[i]",array_1[i]);
    var kurasu = {array_1:array_1[i],array_2:array_2[i] };

kurasulst.push(kurasu);
}

please help me on this.

You can use reduce and map

var output = array_1.reduce( ( a, c ) => a.concat( array_2.map( s => [c,s] ) ),  []);

Demo

 var array_1 = [1,2,3]; var array_2 = ["a","b"]; var output = array_1.reduce( (a, c) => a.concat(array_2.map( s => [c,s] )), []); console.log( output ); 

Try this:

var kurasulst = [];
for (var i = 0; i < array_1.length; i++) {
    for (var j = 0; j < array_2.length; j++) {
        kurasulst.push([array_1[i], array_2[j]]);
    }
}
console.log(kurasulst);

You can do the following:

 var array_1 = [1,2,3]; var array_2 = ['a','b']; var res = []; array_1.forEach(function(item){ res2 = array_2.forEach(function(data){ var temp = []; temp.push(item); temp.push(data); res.push(temp); }); }); console.log(res); 

You could use an other approach with an arbitrary count of array (kind sort of), like

 var items = [[1, 2, 3], ['a', 'b']], result = items.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), [])); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

With more than two

 var items = [[1, 2, 3], ['a', 'b'], ['alpha', 'gamma', 'delta']], result = items.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), [])); console.log(result.map(a => a.join())); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM