🚀 优质资源分享 🚀
学习路线指引(点击解锁) | 知识定位 | 人群定位 |
---|---|---|
🧡 Python实战微信订餐小程序 🧡 | 进阶级 | 本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯云部署上线,打造一个全栈订餐系统。 |
💛Python量化交易实战💛 | 入门级 | 手把手带你打造一个易扩展、更安全、效率更高的量化交易系统 |
前言
数组去重在面试和工作中都是比较容易见到的问题。
这篇文章主要是来测试多个方法,对下面这个数组的去重结果进行分析讨论。如果有不对的地方,还请大家指出。
const arr = [ 1, 1, "1", "1", 0, 0, "0", "0", true, false, "true", "false", "a", "A", undefined, undefined, "undefined", null, null, 'null', NaN, NaN, +0, -0, new String("1"), new String("1"), Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], [] ];
特殊类型
console.log(1 == "1"); // true
console.log(1 === "1"); // false
console.log(0 == "0"); // true
console.log(0 === "0"); // false
console.log(0 == +0); // true
console.log(0 === +0); // true
console.log(0 == -0); // true
console.log(0 === -0); // true
console.log(+0 == -0); // true
console.log(+0 === -0); // true
console.log(0 == false); // true
console.log(0 === false); // false
console.log(0 == undefined); // false
console.log(0 === undefined); // false
console.log(0 == null); // false
console.log(0 === null); // false
console.log(1 == true); // true
console.log(1 === true); // false
console.log(undefined == null); // true
console.log(undefined === null); // false
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
console.log(new String("1") == new String("1")); // false
console.log(new String("1") === new String("1")); // false
Object.prototype.toString.call(new String('1')) // '[object String]'
console.log(/a/ == /a/); // false
console.log(/a/ === /a/); // false
Object.prototype.toString.call(/a/); //'[object RegExp]'
console.log(Symbol(1) == Symbol(1)); // false
console.log(Symbol(1) === Symbol(1)); // false
console.log({} == {}); // false
console.log({} === {}); // false
console.log([] == []); // false
console.log([] === []); // false
接下来,我们看看下面多个去重方法,对以上特殊类型的去重效果。
代码一(暴力解法)
// 暴力解法一
function unique(array) {
if (!Array.isArray(array)) {
console.log("type error!");
return;
}
const res = [array[0]];
let arrLen = array.length;
let resLen = res.length;
for (let i = 0; i < arrLen; i++) {
let flag = true;
for (let j = 0; j < resLen; j++) {
if (array[i] === res[j]) {
flag = false;
break;
}
}
if (flag) {
res.push(array[i]);
resLen = res.length;
}
}
return res;
}
// [1, &#