JavaScript - all possible combinations of arrays

Hey, I have this example:

var arr = [['USA', 'Canada'], ['Food', 'Sports']];

and expected result:

arr = [
  ['USA', 'Food'],
  ['USA', 'Sports'],
  ['Canada', 'Food'],
  ['Canada', 'Sports']
];

Not how I did it, it was like this:

var newArr = [];
$.each(arr[0], function (i, item) {
  $.each(arr[1], function (i, thisItem) {
    newArr.push([item, thisItem]);
  });
});

But this will not work when I add additional elements to the address.

Is there a way to make this recursive, no matter how many levels we have?

+4
source share
1 answer

This is called a product cartesian.

To do this, you can use the functions ES6: reduceand map.

In set theory (and, as a rule, in other parts of mathematics), the Cartesian product is a mathematical operation that returns a set of several sets.

function cartesianProduct(array) {
  return array.reduce((a, b) =>
    a.map(x => b.map(y => x.concat(y)))
    .reduce((a, b) => a.concat(b), []), [[]]);
}
console.log(cartesianProduct([['USA', 'Canada'], ['Food', 'Sports']]));
Run codeHide result

, .

function cartesianProduct(...array) {
      return array.reduce((a, b) =>
        a.map(x => b.map(y => x.concat(y)))
        .reduce((a, b) => a.concat(b), []), [[]]);
}
console.log(cartesianProduct(['USA', 'Canada'], ['Food', 'Sports']));
Hide result
+6

Source: https://habr.com/ru/post/1688453/


All Articles