笛卡尔乘积指数学中,X和Y两个集合的笛卡尔积。表示为X × Y,第一个对象是X的成员,第二个对象是Y的所有可能有序对的其中一个成员 。
假设X=[A,B,C]
,Y=[1,2,3]
那么X与Y的笛卡尔积为[A1,A2,A3,B1,B2,B3,C1,C2,C3]
。
使用Javascript实现Sku算法的方式为:
//假设一个商品有两种规格,[3个颜色],[3个尺码]。3*3=9个SKU
let spec = [
["红","绿","蓝"],
["大","中","小"]
]
let sku = spec.reduce((x,y) =>{
let arr = [];
x.forEach(x => y.forEach(y => arr.push(x.concat([y]))))
return arr;
},[[]])
console.log(sku)
//输出
/**
[
["红","大"],
["红","中"],
["红","小"],
["绿","大"],
["绿","中"],
["绿","小"],
["蓝","大"],
["蓝","中"],
["蓝","小"]]
*/
例:2 * 3 * 4 * 5 = 120个SKU
let spec = [
[
{attr:"颜色",value:"红色"},
{attr:"颜色",value:"绿色"}
],
[
{attr:"尺码",value:"S"},
{attr:"尺码",value:"M"},
{attr:"尺码",value:"L"}
],[
{attr:"重量",value:"100"},
{attr:"重量",value:"200"},
{attr:"重量",value:"300"},
{attr:"重量",value:"400"}
],
[
{attr:"年份",value:"2022"},
{attr:"年份",value:"2021"},
{attr:"年份",value:"2020"},
{attr:"年份",value:"2019"},
{attr:"年份",value:"2018"}
],
]
//120个SKU
更多方法欢迎交流~