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.

2

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.