Generation cartesian product objects from array values

I'm building an array of objects out of the permutations of the entries in some arrays. My first stab at the code is below, it should help to illustrate what I'm trying to achieve:

permutationsArray = (array1, array2, array3) => {
  const arrayOfObjects = [];
    for (let i = 0; i < array1.length; i++) {
      for (let j = 0; j < array2.length; j++) {
        for (let k = 0; k < array3.length; k++) {
          arrayOfObjects.push({
            aConstant: 'some constant',
            key1: array1[i],
            key2: array2[j],
            key3: array3[k],
          });
        }
      }
    }
  return arrayOfObjects;
};

I'm really unhappy with having nested for loops to achieve this. Alternatives I have looked at are:

  • Use nested mapping and flatten the tree created
  • Attempt a recursive system similar to this solution here

I'm looking for input as to whether I'm going in the right direction with solving this. Ideally I want to get to the point where I can supply as many arrays as I wanted.

A big problem I'm seeing is how to name the keys with recursion.

Answers:

Answer

First of all, that's not a problem with permutations, it's exactly Cartesian product.

In set theory (and, usually, in other parts of mathematics), a Cartesian product is a mathematical operation that returns a set from multiple sets.

enter image description here

You can achieve that using ES6 features like map and reduce methods.

function cartesianProduct(...arrays) {
  return [...arrays].reduce((a, b) =>
    a.map(x => b.map(y => x.concat(y)))
    .reduce((a, b) => a.concat(b), []), [[]]);
}
console.log(cartesianProduct([1, 2], [3, 4], [5, 6]));

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.