码迷,mamicode.com
首页 > 编程语言 > 详细

数组去重

时间:2021-04-29 11:48:15      阅读:0      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!