2

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.

Avi Tshuva
  • 246
  • 2
  • 12
tenten
  • 1,276
  • 2
  • 26
  • 54
  • 1
    one thing, `rowCount` is not a sum, but a product (you're basically doing a cartesian product). – cosh Feb 08 '18 at 11:23
  • Possible duplicate of [Javascript - Generating all combinations of elements in a single array (in pairs)](https://stackoverflow.com/questions/43241174/javascript-generating-all-combinations-of-elements-in-a-single-array-in-pairs) – Redu Apr 23 '18 at 21:13

4 Answers4

3

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 );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

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);
karaxuna
  • 26,752
  • 13
  • 82
  • 117
1

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);
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392