Haloor Haloor - 3 months ago 11
Javascript Question

how to generate all pairwise combinations between two arrays of unequal length in JavaScript?

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

Answer

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

Comments