js 数组去重,能用几种方法实现

172 阅读1分钟

方法1: 使用 es6 set 方法 [...new Set(arr)]

let arr = [0,0,5,5,9,8,1,5,4]

let uniqq = [...new Set(arr)]

// 利用set里面元素不能重复的特性进行去重

console.log(uniqq) // [0,5,9,8,1,4]

方法2:利用indexOf()查找是否有相同元素

let arr = [0,0,5,5,9,8,1,5,4]

    const unique = []

    for(var key of arr) {

        // 如果在数组中没找到该元素,则会返回-1

       unique.indexOf(key) === -1 && unique.push(key)

    }

    console.log(unique); // [0,5,9,8,1,4]

方法3:利用filter过滤数组

let arr = [0,0,5,5,9,8,1,5,4]

let unique = arr.filter((it,index)=> {

    // 如果结果为true,则会返回该元素

   return arr.indexOf(it) === index

})

console.log(unique); // [0, 5, 9, 8, 1, 4]

方法4:利用 Map 数据结构去重

    let arr = [0, 0, 5, 5, 9, 8, 1, 5, 4]

    // Map 对象保存键值对,并且能够记住键的原始插入顺序。任何值(对象或者原始值) 都可以作为一个键或一个值。

    let seen = new Map();

    const unique = arr.filter((item) => {

        // 方法has() 返回一个bool值,用来表明map 中是否存在指定元素.

        // set() 方法为 Map 对象添加或更新一个指定了键(key)和值(value)的(新)键值对。

        return !seen.has(item) && seen.set(item,1);

    });

    console.log(unique); // [0, 5, 9, 8, 1, 4]

方法5:利用循环和includes

    let arr = [0, 0, 5, 5, 9, 8, 1, 5, 4]

    let unique = []

    for (var key of arr) {

        !unique.includes(key) && unique.push(key)

    }

    console.log(unique);

方法6:双重for循环和splice

let arr = [0, 0, 5, 5, 9, 8, 1, 5, 4]

    for (var i = 0; i < arr.length; i++) {

        for (var j = i + 1; j < arr.length; j++) {

            if (arr[i] == arr[j]) {

                //第一个等同于第二个,splice 方法删除第二个

                arr.splice(j, 1); j--;

            }

        }

    }

    console.log(arr); // [0, 5, 9, 8, 1, 4]