js对象数组/字符串数组去重

1.根据对象某一key值去重:

1.保留前面的重复值

/**
        * @description: 数组根据某一key值去重
        * @param {*} arr
        * @param {*} property
        * @return {*}
        * @author: Simoon.jia
        */
    const unique = (arr, property) => {
        let obj = {};
        return arr.reduce(function (preValue, item) {
            obj[item[property]] ? '' : (obj[item[property]] = true && preValue.push(item));
            return preValue;
        }, []);
    };

2.后面的重复值覆盖前面的

/**
        * @description: js数组根据某一key值去重,后面的重复值覆盖之前的
        * @param {*} arr
        * @param {*} property
        * @return {*}
        * @author: Simoon.jia
        */
    const unique = (arr, property) => {
        let obj = {};
        return arr.reduce(function (preValue, item) {
            obj[item[property]] = item;
            return Object.values(obj);
        }, []);
    };

 

使用:

 let newCabinetAlarm = unique(alarmList, "cabinetId")

 

2.可以使用 Set 和 Array.from 方法来实现对象数组去重:

function unique(arr) {
  return Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
}
 
这个方法的原理是将对象数组转换成字符串数组,然后使用 Set 去重,最后再将字符串数组转换成对象数组。需要注意的是,使用 JSON.stringify 和 JSON.parse 转换对象数组时,需要对象中的属性顺序相同才能正确转换。
 
 
 

!字符串数组去重

✅ 方式一(最推荐):Set

适合:简单、性能好、可读性强

原理
Set 天然不允许重复值(基于 SameValueZero)

const arr = ['a', 'b', 'a', 'c', 'b'];

const uniqueArr = [...new Set(arr)];

console.log(uniqueArr); // ['a', 'b', 'c']

 

✅ 方式二:filter + indexOf

适合:需要兼容老环境

const uniqueArr = arr.filter((item, index) => {
  return arr.indexOf(item) === index;
});

✅ 方式三:reduce

适合:想顺便做统计或额外逻辑

const uniqueArr = arr.reduce((res, item) => {
  if (!res.includes(item)) {
    res.push(item);
  }
  return res;
}, []);

 

✅ 方式四:使用对象(不推荐但要会)

const uniqueArr = [];
const map = {};

for (const item of arr) {
  if (!map[item]) {
    map[item] = true;
    uniqueArr.push(item);
  }
}

缺点

  • 原型污染风险

  • __proto__ 等特殊键问题

⚠️ 注意事项(很重要)

1️⃣ 大小写是否区分?

 
['A', 'a']. → 是否算重复?

忽略大小写去重:

 
const uniqueArr = [...new Set(arr.map(i => i.toLowerCase()))];

2️⃣ 去重但保持原顺序?

👉 上面 所有方案都保持顺序(除了你主动排序)


3️⃣ 性能对比(大数据量)

方法 时间复杂度
Set ⭐ 最优
filter O(n²)
reduce O(n²)

✅ 推荐结论

90% 场景直接用 Set

 
const unique = arr => [...new Set(arr)];

如果你是:

  • Vue / React 里用

  • 数组很大(上万条)

  • 需要按某个规则去重(如忽略空格 / 忽略大小写)

你可以把具体场景贴出来,我可以直接帮你写最合适的一版 👍

posted @ 2023-02-07 16:23  SimoonJia  阅读(3)  评论(0)    收藏  举报