reduce 实现笛卡尔算法

35 阅读1分钟

1.使用Reduce函数来对算法进行升级优化

​..reduce() 方法接收一个函数作为累加器,
..数组中的每个值(从左到右)开始缩减,最终计算为一个值。
..原理是一个递归,但是使用reduce会更简单

 一、数组求和

const ary= [1,2,3,4,5]
// 0 表示第一个元素为零即prev第一次是0
const gentleNum = ary.reduce( (prev,next,index)=>{return prev + next} , 0)

二、reduce生商品sku(笛卡尔算法,数组类型数据)

const skuValue= [
    ['红', '黄', '蓝'],
    ['S', 'M'],
    ['100ML', '200ML'],
]
const result = skuValue.reduce((prev, next, index) => {    const res = []
    prev.map(p => {        next.map(n => {
            res.push([...p, n])
        })
    })
    return res
}, [[]])
console.log(result)
/*
 [['红', 'S', '100ML'],
 ['红', 'S', '200ML'],
 ['红', 'M', '100ML'],
 ['红', 'M', '200ML'],
 ['黄', 'S', '100ML'],
 ['黄', 'S', '200ML'],
 ['黄', 'M', '100ML'],
 ['黄', 'M', '200ML'],
 ['蓝', 'S', '100ML'],
 ['蓝', 'S', '200ML'],
 ['蓝', 'M', '100ML'],
 ['蓝', 'M', '200ML']]

*/

三、reduce生商品sku(笛卡尔算法,对象类型数据)

const skuObj = [{name:'颜色',values:['红', '黄', '蓝']},{name:'尺寸',values:['S','M']}]


const result = skuObj.reduce((prev, next, c) => {    let res=[]
    prev.map(p=>{
        next.values.map(n=>{            res.push({...p,[next.name]:n})
        })
    })
    return res
},[{}])
console.log(result)
/*
[{颜色: '红', 尺寸: 'S'},
 {颜色: '红', 尺寸: 'M'},
 {颜色: '黄', 尺寸: 'S'},
 {颜色: '黄', 尺寸: 'M'},
 {颜色: '蓝', 尺寸: 'S'},
 {颜色: '蓝', 尺寸: 'M'}]
*/