[英]linq for js: how to get cartesian product of multiple arrays
我有一个不可预测数量的数组,如下图所示。
使用 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.
我怎样才能实现它?
对于结果中想要的每个数组,只需添加一个 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();
这相当于查询语法:
from a in data[0]
from b in data[1]
from c in data[2]
select [a, b, c]
您可以使用以下简单的两行函数来生成任意数量数组的笛卡尔积:
// 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.