数组对象去重

1.对于数组去重一般会选用es6中的includes方法,但是这种只适用于数组中的元素为非对象的情形;对于数组中包含的对象一般采用reduce;

reduce使用方法:

定义:

array.reduce(function(total, currentValue, currentIndex, array), initialValue);

reduce方法会遍历数组,并且为数组中的每个元素,执行定义的callback方法,并把结果汇总为单个值返回。

参数定义

callback:为每个元素执行的方法,它有以下四个参数

   total:累计器,也是最终返回的结果

   currentValue:当前遍历的元素

   currentIndex:当前遍历的元素的下标,可选

   array:原始数组,可选

initialValue:初始值

需要注意的是,如果定义了initialValue,那么total的初始值就是initialValue,遍历则从第0项开始。

如果没有定义,则total的初始值,会是第0项元素,遍历则从第1项开始。

 /* 去重函数 ES5的对象 */
    uniqueKeyValue(arr, key) {
      const has = {}
      const uniqueResult = arr.reduce((total, currentValue) => {
        if (!has[currentValue[key]]) {
          has[currentValue[key]] = true
          total.push(currentValue)
        }
        return total
      }, [])
      return uniqueResult
    },
posted @ 2019-11-22 18:07  我自浮沉,虚浮自我  阅读(217)  评论(0编辑  收藏  举报