jeudi 26 octobre 2017

Generation of an array of objects with permutations of 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.

Aucun commentaire:

Enregistrer un commentaire