1

I'm looking for method to find cartesian array based on array of objects.

Basicly I've seen solutions like that:

Cartesian product of multiple arrays in JavaScript

but I'm not sure how to modify it to work on object property (in my case on property "value").

For instance my input:

let arr1 = [
  {
    id: 1,
    type: "attribute",
    value: "arr1-attr1"
  },
  {
    id: 2,
    type: "attribute",
    value: "arr1-attr2"
  }
];

let arr2 = [
  {
    id: 3,
    type: "attribute",
    value: "arr2-attr1"
  }
];

let arr3 = [
  {
    id: 4,
    type: "attribute",
    value: "arr3-attr1"
  },
  {
    id: 5,
    type: "attribute",
    value: "arr3-attr2"
  }
];

Expected output:

output = [
  [
    {
      id: 1,
      type: "attribute",
      value: "arr1-attr1"
    },
    {
      id: 3,
      type: "attribute",
      value: "arr2-attr1"
    },
    {
      id: 4,
      type: "attribute",
      value: "arr3-attr1"
    }
  ],
  [
    {
      id: 2,
      type: "attribute",
      value: "arr1-attr2"
    },
    {
      id: 3,
      type: "attribute",
      value: "arr2-attr1"
    },
    {
      id: 5,
      type: "attribute",
      value: "arr3-attr2"
    }
  ],
  [
    {
      id: 1,
      type: "attribute",
      value: "arr1-attr1"
    },
    {
      id: 3,
      type: "attribute",
      value: "arr2-attr1"
    },
    {
      id: 4,
      type: "attribute",
      value: "arr3-attr1"
    }
  ],
  [
    {
      id: 2,
      type: "attribute",
      value: "arr1-attr2"
    },
    {
      id: 3,
      type: "attribute",
      value: "arr2-attr1"
    },
    {
      id: 5,
      type: "attribute",
      value: "arr3-attr2"
    }
  ]
];
nextest
  • 35
  • 5

1 Answers1

1

Just take the single arrays as items of a collection of this arrays and perform the algorithm on this data set.

var arr1 = [{ id: 1, type: "attribute", value: "arr1-attr1" }, { id: 2, type: "attribute", value: "arr1-attr2" }],
    arr2 = [{ id: 3, type: "attribute", value: "arr2-attr1" }],
    arr3 = [{ id: 4, type: "attribute", value: "arr3-attr1" }, { id: 5, type: "attribute", value: "arr3-attr2" }],
    result = [arr1, arr2, arr3]
        .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392