reduce
作用: 可以有一个临时变量记录(参数pre),遍历时进行转换记录,最后返回出想要的数据结果
let arr = [
{name: ‘zs’, age: ‘12’, num: ‘1601’},
{name: ‘ls’, age: ‘13’, num: ‘1602’},
{name: ‘ys’, age: ‘12’, num: ‘1603’},
{name: ‘wx’, age: ‘14’, num: ‘1604’},
{name: ‘zs’, age: ‘12’, num: ‘1605’},
]
场景: 改造数组
// 1,reduce对数组进行筛选 如:要求将名字一致的划为一组 添加到children中
const res = arr.reduce((pre, cur) => {
let index = pre.findIndex(e => e.name === cur.name)
if (index > -1) {
pre[index].children.push(cur)
} else {
pre.push({
name: cur.name,
children: [cur]
})
}
return pre
}, [])
console.log(res)
// 2筛选出每一项中的某一个元素
const res2 = arr.reduce((pre, cur) => {
if(!pre.includes(cur.name)) {
pre.push(cur.name)
}
return pre
},[])
console.log(res2)
// map实现
const arr3 = []
const res3 = arr.map((item, index) => {
if(!arr3.includes(item.name)) {
arr3.push(item.name)
}
})
console.log(arr3)