一些数组去重解决方案(简)

    科技2025-08-13  7

    去重的方法很多,不同的时候可以用不同的方法;关键是用什么判断两个值相等。

    Set:不能去一样的对象 双等号:不能去一样的对象,NaN indexOf:不能去一样的对象,NaN 对象键名:不能去true includes:不能去对象 hasOwnProperty: map.has:不能去NaN

    自己实现了一种,效率较低

    var arr = [, , 0b001, -Infinity, Infinity, +Infinity, 1, 1, 'true', +0, -0, [], [], [0],Symbol("foo"),Symbol("f"), [0], 0, 'true', true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN, 'NaN', 0, 0, 'a', 'a', {}, {}, { b: [{ c: null }], a: 1, }, { a: 1, b: [{ c: null }] }, ]; function uniqueArr(arr) { /** * 数组去重,看上去是重复的就可以去重 * 不支持IE,不支持BigInt, * 对象的键的顺序会有影响 */ var obj = {}; arr.map(e => { obj[Object.prototype.toString.call(e) + JSON.stringify(e) + String(e)] = e;// typeError:JSON.stringify(1n); }); return Object.values(obj); //not IE } console.log(uniqueArr(arr))
    Processed: 0.013, SQL: 8