数组去重

134 阅读2分钟

1.数组每一项都为 基本类型

这种应用场景一般有 下拉框选中值的数据处理checkbox选中值处理 等等.
比较简单的处理方式为 new Set() 一把梭.

const list = [undefined, 1, '', null, true, undefined, 1,  '', null, true]
const _list = [...new Set(list)] // [ undefined, 1, '', null, true ]

2.数组每一项都为 引用类型

这种一般应用场景有 列表接口返回重复数据需要前端去重提交给接口的数据需要去重.
这种数据一般会从一个属性 attributes 来去重,可能是 id,name...
这里选用 BIG 较高的 Array.reduce() 函数处理.

  1. 创建一个空对象 obj 等会要用
  2. 使用 Array.reduce() 循环 list
  3. 判断 list 的每一项 currentValue 的某一个 attributes 是否存在于 obj
  4. 存在就不处理,不存在就把这一项扔到 Array.reduce() 中的 previousValue 中,同时将该 attributes 塞到 obj 中,表示这个 attributes 已经存在过.

直接上代码

// previousValue: 上一次调用 callbackFn 时的返回值。在第一次调用时,若指定了初始值,其值则为 initialValue,否则为数组索引为 0 的元素 array[0]
// initialValue: 上一次调用 callbackFn 时的返回值
// currentValue: 数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1]
// currentIndex: 数组中正在处理的元素的索引。若指定了初始值 initialValue,则起始索引号为 0,否则从索引 1 起始
// array: 用于遍历的数组

// list: 待处理数组
// attributes: 要过滤的属性id/name...

const filterRepeatData = (list = [], attributes = null) => {
    let obj = {}
    return list.reduce((previousValue, currentValue, currentIndex, array) => {
        obj[currentValue[attributes]]
            ? ""
            : (obj[currentValue[attributes]] =
                true && previousValue.push(currentValue))
        return previousValue
    }, [])
}

测试一下

const list = [
    { id: 1, name: 1 },
    { id: 1, name: 2 },
    { id: 2, name: 2 },
]
const res = filterRepeatData(list, "name");
console.log(res) // [{ id: 1, name: 1 }, { id: 1, name: 2 }]