js reduce()方法 配合 RegExp正则模糊匹配

本文深入探讨了JavaScript数组中的reduce方法使用技巧,通过实例详细解释如何利用reduce方法实现数组对象去重,特别关注于合并相同examid的项并确保answer属性值不重复。文章提供了完整的代码示例和相关资源链接,帮助读者掌握reduce方法的高级应用。

这里提供一个小需求,需要将 examid 相同的项合并,并将此项中的 answer 属性值合起来且不重复
具体数据如下:

state = {
	arr: [
              { examid: '1052', stb: '1', optionid: '4199', answer: 'A' },
              { examid: '1265', stb: '1', optionid: '5051', answer: 'A' },
              { examid: '970', stb: '1', optionid: '3871', answer: 'A' },
              { examid: '875', stb: '1', optionid: '3491', answer: 'A' },
              { examid: '1174', stb: '1', optionid: '4687', answer: 'A' },
              { examid: '1017', stb: '1', optionid: '4059', answer: 'AB' },
              { examid: '1017', stb: '1', optionid: '4060', answer: 'B' },
              { examid: '1096', stb: '1', optionid: '4375', answer: 'AB' },
              { examid: '1096', stb: '1', optionid: '4376', answer: 'B' },
              { examid: '856', stb: '1', optionid: '3421', answer: 'AB' },
              { examid: '856', stb: '1', optionid: '3422', answer: 'B' },
              { examid: '1059', stb: '1', optionid: '4227', answer: 'AB' },
              { examid: '1059', stb: '1', optionid: '4228', answer: 'B' },
              { examid: '1039', stb: '1', optionid: '4147', answer: 'AB' },
              { examid: '1039', stb: '1', optionid: '4148', answer: 'c' }
          ]
}
public xxx = ()=>{
    console.log(this.state.arr,'arr');
    let newObj = {}
    let newArr = this.state.arr.reduce((item: any,currentValue) => {
    
      // 先判断是否重复
      if (newObj[currentValue.examid]) {

		// 重复,则判断 answer 属性中是否已有当前项的 answer 值,通过正则模糊匹配
        let answer = currentValue.answer
        let reg = new RegExp(answer)
        if (!item[newObj[currentValue.examid]-1].answer.match(reg)) {
          item[newObj[currentValue.examid]-1] = {...item[newObj[currentValue.examid]-1], answer: item[newObj[currentValue.examid]-1].answer + currentValue.answer}
        }
      } else {
		
		// 未重复,则将当前项加入到数组中
        newObj[currentValue.examid] = item.push(currentValue)
      }
      return item
    },[])
    console.log(newArr,'newArr');
  }

结果:
在这里插入图片描述
更多可参考:
JS数组中 reduce() 方法 数组对象去重: https://blog.youkuaiyun.com/AS_TS/article/details/108060856
JS数组reduce()方法详解及高级技巧: https://blog.youkuaiyun.com/AS_TS/article/details/108060636
前端模糊匹配方式,前端正则模糊匹配: https://blog.youkuaiyun.com/AS_TS/article/details/108056652

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值