请列出几种数组去重方法,并举例说明

数组去重方法

数组去重的方法有很多种,下面列出了几种常见的方法。

ES6 Set数据结构去重

这种方法是在面试中最常提到的,也是最简单的方法。

利用ES6 Set数据结构,通过将原始数组转换成Set,然后通过Set的自动去重特性,将数组中的重复元素去除。

const arr = [1, 1, 2, 3, 5, 6, 6, 7, {
    
    }, {
    
    }, {
    
    name: 'liu'}];
const newArr = Array.from(new Set(arr));
console.log(newArr); // [1, 2, 3, 5, 6, 7, {}, {name: 'liu'}]

注意,这种方法只适用于原始类型的数据,例如数字、字符串等,对于对象类型的数据则不适用。

因为Set只能存储不可重复的元素,如果元素本身是可变的,那么在Set中就不能保证唯一性。

双重for循环去重

这是最基础的方法,通过一个双重for循环,将新数组newArr清空,然后遍历原数组arr,如果原数组中当前元素与新数组中已有元素不同,则将其添加到新数组中。

function newArrFn(arr) {
    
    
    let newArr = [];
    for (let i = 0; i < arr.length; i++) {
    
    
        let flag = false;
        for (let j = 0; j < newArr.length; j++) {
    
    
            if (arr[i] === newArr[j]) {
    
    
                flag = true;
                break;
            }
        }
        flag ? newArr.push(arr[i]) : null;
    }
    return newArr;
}
console.log(newArrFn(arr)); // [1, 2, 3, 5, 6, 7, {}, {name: 'liu'}]

这种方法的缺点是效率较低,时间复杂度为O(n^2),在处理大数据量时可能会出现性能问题。

for循环 + findIndex去重

这个方法利用 findIndex 的特性,查找元素找不到就返回-1,接下来判断如果返回值是-1,说明没找到,就往新数组里面添加元素。

这种方法相较于双重for循环有一定的性能提升。

let arr = [1, 2, 3, 4, 5, 4, 3, 2, 1];
let newArr = [];
for (let i = 0; i < arr.length; i++) {
    
    
    let index = newArr.findIndex(item => item === arr[i]);
    if (index === -1) {
    
    
        newArr.push(arr[i]);
    }
}
console.log(newArr); // [1, 2, 3, 4, 5]

但是,这种方法依然存在性能问题,当数组中存在大量重复元素时,findIndex方法会进行大量的无效查找,导致效率降低。

findIndex

扫描二维码关注公众号,回复: 17297865 查看本文章

findIndex 是 JavaScript 数组的一个方法,用于找到满足指定条件的数组元素的索引位置。它接受一个回调函数作为参数,并返回满足条件的第一个元素的索引,如果没有找到满足条件的元素,则返回 -1。

以下是 findIndex 方法的语法:

array.findIndex(callback(element[, index[, array]])[, thisArg])
  • callback:要执行的函数,它接收三个参数:

    • element:当前被处理的元素。
    • index(可选):当前被处理的元素的索引。
    • array(可选):调用 findIndex 方法的数组。
  • thisArg(可选):传递给回调函数的 this 值。

下面是一个例子,演示如何使用 findIndex 方法查找数组中第一个大于 5 的元素的索引:

const arr = [2, 4, 6, 8, 10];
const index = arr.findIndex((element) => element > 5);
console.log(index); // Output: 2

在上面的例子中,回调函数 (element) => element > 5 用于判断数组元素是否大于 5。findIndex 方法会从头开始遍历数组,当找到第一个满足条件的元素时,返回该元素的索引位置。在这个例子中,第一个大于 5 的元素是 6,所以返回它的索引 2。如果数组中没有满足条件的元素,则返回 -1。

findIndex 方法是 ES6 引入的新特性,所以在一些旧版本的浏览器上可能不被支持。在使用之前,请确保你的目标环境支持该方法或者提供一个适当的 polyfill。

使用filter和indexOf方法

通过遍历原始数组,利用indexOf方法判断当前元素在新数组中是否已存在,如果不存在则添加到新数组中

const arr = [1, 2, 2, 3, 3, 4];
const uniqueArr = arr.filter((item, index) => {
    
    
  return arr.indexOf(item) === index;
});
console.log(uniqueArr); // Output: [1, 2, 3, 4]

使用reduce方法

通过reduce方法遍历原始数组,将每个元素添加到一个新数组中,但仅在新数组中不存在该元素的情况下才添加。

const arr = [1, 2, 2, 3, 3, 4];
const uniqueArr = arr.reduce((unique, item) => {
    
    
  return unique.includes(item) ? unique : [...unique, item];
}, []);
console.log(uniqueArr); // Output: [1, 2, 3, 4]

更多详细内容,请微信搜索“前端爱好者戳我 查看

猜你喜欢

转载自blog.csdn.net/BradenHan/article/details/135007138