Pablo Gablo
Pablo Gablo

Reputation: 55

linq for js: how to get cartesian product of multiple arrays

I have an unpredictable number of arrays as showed on the picture below.

arrays

Using linq for js I would like to get a Cartesian product of these arrays ie.

{
    {AttributeTypeId: 10, AttributeId: 34, AttributeName: "b11  13-128"}
    {AttributeTypeId: 11, AttributeId: 56, AttributeName: "21/uk4"},
    {AttributeTypeId: 13, AttributeId: 69, AttributeName: "Boy"}
},
    {AttributeTypeId: 10, AttributeId: 33, AttributeName: "b10  13-128"},
    {AttributeTypeId: 11, AttributeId: 56, AttributeName: "21/uk4"},
    {AttributeTypeId: 13, AttributeId: 69, AttributeName: "Boy"}
},
{
    {AttributeTypeId: 10, AttributeId: 38, AttributeName: "G01  13-102"},
    {AttributeTypeId: 11, AttributeId: 56, AttributeName: "21/uk4"},
    {AttributeTypeId: 13, AttributeId: 69, AttributeName: "Boy"}
},
{
    {AttributeTypeId: 10, AttributeId: 34, AttributeName: "b11  13-128"},
    {AttributeTypeId: 11, AttributeId: 54, AttributeName: "19/uk3"},
    {AttributeTypeId: 13, AttributeId: 69, AttributeName: "Boy"}
}
....
etc.

How can I achieve it ?

Upvotes: 0

Views: 194

Answers (2)

ru13r
ru13r

Reputation: 194

You can use the following simple two-line function to make a Cartesian product of any number of arrays:

// cartesian product of arrays
const cartesian = (...arrays) => arrays.reduce((a, b) => 
  [].concat(...a.map(a => b.map(b => [].concat(a, b)))));

// usage example
const arr1 = [1, 2, 3];
const arr2 = ['a', 'b'];
const arr3 = [true, false];

console.log(cartesian(arr1, arr2, arr3));

Upvotes: 0

Jeff Mercado
Jeff Mercado

Reputation: 134841

For every array you want in the result, just add a select many.

var result = Enumerable.from(data[0]).selectMany(a =>
    Enumerable.from(data[1]).selectMany(b =>
        Enumerable.from(data[2]).select(c =>
            [a, b, c]
        )
    )
).toArray();

This is the equivalent to the query syntax:

from a in data[0]
from b in data[1]
from c in data[2]
select [a, b, c]

Upvotes: 1

Related Questions