reduce()方法详解之数组对象去重

1.reduce()方法实现数组对象去重(reduce方法没搞明白过)

// 测试
    getTest1() {
    
    
      const array1 = [
        {
    
     userId: 12277, insuranceProbability: '0.55', nonInsuranceProbability: '0.33' },
        {
    
     userId: 10253, insuranceProbability: '0.65', nonInsuranceProbability: '0.38' },
        {
    
     userId: 12277, insuranceProbability: '0.55', nonInsuranceProbability: '0.33' },
        {
    
     userId: 10253, insuranceProbability: '0.65', nonInsuranceProbability: '0.38' },
        {
    
     userId: 12277, insuranceProbability: '0.55', nonInsuranceProbability: '0.33' }
      ]
      const obj = {
    
    }
      const open = array1.reduce((total, item) => {
    
    
        console.log(total, '111')
        console.log(item, '222')
        obj[item.userId] ? '' : obj[item.userId] = true && total.push(item)
        return total
      }, [])
      console.log(open, 'open----')
    }
  }

打印结果
在这里插入图片描述
(reduce使用详解:默认穿了个空数组,那ruduce第一个参数total就默认是空数组,第二个参数item拿的是array数组的第一项,若是不传默认值,则total拿的是array数组的第一项,item拿的是数组的第二项,reduce函数内需要给return值,因为total下一下拿的就是return的值,若没有则total打印的是undefined,第二个参数item还是会依次去取array后面几项的值,一般数组求和用reduce是真香)

2.数组对象相同id的进行数据合并代码拿的这个小可爱的
(userId是一样的,但是其它的值不一样的话,我想拿到最终的修改值)

getTest2() {
    
    
      const array = [
        {
    
     userId: 12277, insuranceProbability: '0.51', nonInsuranceProbability: '0.33' },
        {
    
     userId: 10253, insuranceProbability: '0.65', nonInsuranceProbability: '0.38' },
        {
    
     userId: 12277, insuranceProbability: '0.58', nonInsuranceProbability: '0.39' },
        {
    
     userId: 10253, insuranceProbability: '0.82', nonInsuranceProbability: '0.18' },
        {
    
     userId: 12277, insuranceProbability: '0.58', nonInsuranceProbability: '0.36' }
      ]
      const idList = [] // 存放userId
      const newArray = [] // 新数组
      for (let i = 0; i < array.length; i++) {
    
    
      // 循环array数组
      if (idList.indexOf(array[i].userId) === -1) {
    
    
        // 将第一次出现的userId存到idList
        idList.push(array[i].userId)
        // 第一次出现的userId没有重复,所以该项(array[i])存进newArray
        newArray.push(array[i])
      } else {
    
    
        // 出现重复的userId
        // 将此项覆盖掉newArray内相同userId的那一项
        newArray.splice(idList.indexOf(array[i].userId), 1, array[i])
      }
      console.log(idList, newArray, {
    
     ...newArray })
    }

打印结果:
在这里插入图片描述
最后说一句,ES6真香啊

猜你喜欢

转载自blog.csdn.net/weixin_45324044/article/details/115180453