Skip to content

deDuplication

用于数组去重

配置项

参数类型是否必选默认值参数描述
arrayArray[]源数组
attrString-根据属性进行去重(用于类数组对象,不传则为简单类型数组去重)

返回值

类型描述
Array返回去重后的数组

示例

deDuplication([1,1,1,2,3]) // [1, 2, 3]
let arr = [{label: 1, value: 1}, {label: 1, value: 2}, {label: 1, value: 3}]
deDuplication(arr, 'label') //  [{label: 1, value: 1}]

源码

js
export function deDuplication(array, attr) {
    // 检查输入的 array 是否为数组
    if (!Array.isArray(array)) {
        throw new Error('第一个参数必须是数组');
    }

    // 如果 attr 存在,检查其是否为字符串
    if (attr && typeof attr !== 'string') {
        throw new Error('第二个参数(如果提供)必须是字符串');
    }

    if (attr) {
        const res = new Map();
        return array.filter((item) => {
            // 处理对象属性不存在的情况
            const value = item[attr];
            const shouldInclude = value !== undefined && !res.has(value);
            if (shouldInclude) {
                res.set(value, 1);
            }
            return shouldInclude;
        });
    } else {
        return Array.from(new Set(array));
    }
}