标签:fun for lte UNC -- let nan es6 style
1、利用ES6 Set去重
{}没去重
let arr = [1, 1, ‘true‘, ‘true‘, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN, ‘NaN‘, ‘NaN‘, 0, 0, ‘a‘, ‘a‘, {}, {}]; function unique(arr) { // return [...new Set(arr)] return Array.from(new Set(arr)) } console.log(unique(arr));
// [1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {}, {}]
2.利用indexOf去重
NaN和{}没去重
let arr = [1, 1, ‘true‘, ‘true‘, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN, ‘NaN‘, ‘NaN‘, 0, 0, ‘a‘, ‘a‘, {}, {}]; function unique(arr) { let result = [arr[0]]; for (let i = 1; i < arr.length; i++) { if (result.indexOf(arr[i]) === -1) { result.push(arr[i]); } } return result; } console.log(unique(arr));
// [1, "true", true, 15, false, undefined, null, NaN, NaN, "NaN", 0, "a", {}, {}]
3.利用for嵌套,然后splice去重
NaN和{}没去重
let arr = [2,3,1, 1, ‘true‘, ‘true‘, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN, ‘NaN‘, ‘NaN‘, 0, 0, ‘a‘, ‘a‘, {}, {}]; function unique(arr) { for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { if (arr[i] === arr[j]) { arr.splice(j,1); j--; } } } return arr; } console.log(unique(arr));
4,利用hasOwnProperty
全部去重
let arr = [2, 3, 1, 1, ‘true‘, ‘true‘, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN, ‘NaN‘, ‘NaN‘, 0, 0, ‘a‘, ‘a‘, {}, {}];
function unique(arr) {
let obj = {};
return arr.filter((item, index, arr) => {
return obj.hasOwnProperty(typeof item + item) ? false : obj[typeof item + item] = true;
})
}
console.log(unique(arr));
标签:fun for lte UNC -- let nan es6 style
原文地址:https://www.cnblogs.com/happysummer/p/14714403.html