简体   繁体   English

linq for js:如何获得多个数组的笛卡尔积

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

I have an unpredictable number of arrays as showed on the picture below.我有一个不可预测数量的数组,如下图所示。

数组

Using linq for js I would like to get a Cartesian product of these arrays ie.使用 linq for js 我想得到这些数组的笛卡尔积,即。

{
    {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 ?我怎样才能实现它?

For every array you want in the result, just add a select many.对于结果中想要的每个数组,只需添加一个 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]

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM