-1

I would like to get all possible pair combinations between two arrays. The arrays may or may not be of the same size. For example:

arr1 = ["tom", "sue", "jim"] and arr2 = ["usa", "japan"] would yield the following pairs:

["tom", "usa"]
["tom", "japan"]
["sue", "usa"]
["sue", "japan"]
["jim", "usa"]
["jim", "japan"]

what I have so far is the following code, which does not return all pairs if arrays are unequal lengths:

var pairs= [];
    for (var i = 0; i < arr1.length; i++) {
        for (var j = 0; j < arr2.length; j++) {
                pairs.push(arr1[i] + arr2[j]);
            }
        }
    console.log(pairs);
Haloor
  • 221
  • 4
  • 14

5 Answers5

2

var arr1 = ["tom", "sue", "jim"] 
var arr2 = ["usa", "japan"];

var pairs = arr1.reduce( (p, c) => p.concat(arr2.map( v => [c].concat(v))), [])

console.log(pairs)

As others have noted, your code is fine. I only off this alternative just in case you want to explore other options on how to generate what your needs are.

var arr1 = ["tom", "sue", "jim"], arr2 = ["usa", "japan"];

var pairs = arr1.reduce( (p, c) => p.concat(arr2.map( v => [c].concat(v))), [])

// returns: You have an array OF arrays
[["tom","usa"],
 ["tom","japan"],
 ["sue","usa"],
 ["sue","japan"],
 ["jim","usa"],
["jim","japan"]]
james emanon
  • 11,185
  • 11
  • 56
  • 97
1

Your code is fine. To get the structure similar to how you have it, you can enclose the values in an array.

let arr1 = ["tom", "sue", "jim"];
let arr2 = ["usa", "japan"];

let pairs = [];
for (var i = 0; i < arr1.length; i++) {
  for (var j = 0; j < arr2.length; j++) {
    pairs.push([arr1[i], arr2[j]]);
  }
}
console.log(pairs);
10100111001
  • 1,832
  • 1
  • 11
  • 7
1
var arr1 = ["tom", "sue", "jim"];
var arr2 = ["usa", "japan"];
var pairs = [];

arr1.forEach(x => {arr2.forEach(y => {pairs.push([x, y])})});
console.log(pairs); // [ [ 'tom', 'usa' ],
                       [ 'tom', 'japan' ],
                       [ 'sue', 'usa' ],
                       [ 'sue', 'japan' ],
                       [ 'jim', 'usa' ],
                       [ 'jim', 'japan' ] ]
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
1

Even simplier:

var arr1 = ["tom", "sue", "jim"];
var arr2 = ["usa", "japan"];

pairs = arr1.map(el1 => arr2.map(el2 => [el1, el2]))
console.log(pairs)
0

You can combine the arrays with the following function:

var arr1 = ["tom", "sue", "jim"];
var arr2 = ["usa", "japan"];

function combine() {
    [].sort.call(arguments, (a, b) => b.length - a.length);
    return arguments[0].map(n => arguments[1].map(a => [n, a]));
}

console.log(combine(arr1, arr2));

This will output the following array, holding each possible pair combination in arrays:

[ [ [ 'tom', 'usa' ], [ 'tom', 'japan' ] ],
  [ [ 'sue', 'usa' ], [ 'sue', 'japan' ] ],
  [ [ 'jim', 'usa' ], [ 'jim', 'japan' ] ] ]
baao
  • 71,625
  • 17
  • 143
  • 203