计算数组中每个元素出现的次数
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; const recordTimes = names.reduce((prev, cur) => { if (cur in prev) { prev[cur]++ } else { prev[cur] = 1 } return prev }, {}) console.log(recordTimes)
数组去重
let arr = [1, 2, 3, 4, 4, 1] const unique = arr.reduce((prev, cur) => { if(!prev.includes(cur)){ return prev.concat(cur) }else{ return prev } }, []) console.log(unique)
将二维数组转化为一维
let arr = [[0, 1], [2, 3], [4, 5]] const flatOne = arr.reduce((prev,cur)=>{ return prev.concat(cur) },[]) console.log(flatOne)
将多维数组转化为一维
let arr = [[0, 1], [2, 3], [4, [5, 6, 7]], [2, 3, [2, 3, [2, 3, [2, [2, , [2, 3], 3], 3]]]]] const flatten = arr => { return arr.reduce((prev, cur) => { return prev.concat(Array.isArray(cur) ? flatten(cur) : cur) }, []) } console.log(flatten(arr))
对象里的属性求和
var result = [ { subject: 'math', score: 10 }, { subject: 'chinese', score: 20 }, { subject: 'english', score: 30 } ] const totalSum = result.reduce((prev,cur)=>{ return prev+cur.score },0) console.log(totalSum)