Reputation: 1274
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.
Upvotes: 2
Views: 108
Reputation: 386883
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; }
Upvotes: 1
Reputation: 68933
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);
Upvotes: 1
Reputation: 68443
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 );
Upvotes: 3
Reputation: 26940
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);
Upvotes: 2