reduce

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值