reduce的高级用法
计算数组中每个元素出现的次数
const arr = ['tom', 'alice', 'zoey', 'rain', 'tom']
const num = arr.reduce((prev, cur) => {
if(cur in prev) {
prev[cur] ++
} else {
prev[cur] = 1
}
return prev
}, {})
console.log(num); //{tom: 2, alice: 1, zoey: 1, rain: 1}
数组去重
const arr = ['tom', 'alice', 'zoey', 'rain', 'tom']
const newArr = arr.reduce((prev, curr) => {
if(!prev.includes(curr)) {
prev.push(curr)
}
return prev
}, [])
console.log(newArr); // ["tom", "alice", "zoey", "rain"]
数组扁平化
const arr = [['tom', 'alice'], ['zoey', ['rain', 'tom']]]
const oneDimensionalArr = (arr) => {
return arr.reduce((prev, curr) => {
return prev.concat(Array.isArray(curr) ? oneDimensionalArr(curr) : curr)
}, [])
}
console.log(oneDimensionalArr(arr)); // ["tom", "alice", "zoey", "rain", "tom"]