写一个去除数组中重复元素的函数

1.使用ES6的Set数据结构

Set是一种只存储唯一值的数据结构,因此任何重复的元素都会被自动忽略。然后,我们使用扩展运算符...将Set对象转换回数组,并返回这个新的数组。

请注意,这种方法会改变原始数组中元素的顺序,因为Set不保证元素的插入顺序。如果你需要保持元素的原始顺序,那么你可能需要使用其他方法,例如使用filter()方法和indexOf()方法来检查元素是否已经在结果数组中。

javascript 复制代码
function removeDuplicates(array) {  
    return [...new Set(array)];  
}    

// 使用示例  
const arr = [1, 2, 2, 3, 4, 4, 5, 5, 5];  
const uniqueArr = removeDuplicates(arr);  
console.log(uniqueArr); // 输出: [1, 2, 3, 4, 5]

2.使用filter()方法和indexOf()方法

这种方法通过遍历数组,并使用indexOf()检查当前元素是否首次出现来实现去重。

javascript 复制代码
function removeDuplicates(array) {  
    return array.filter((item, index) => {  
        return array.indexOf(item) === index;  
    });  
}   

const arr = [1, 2, 2, 3, 4, 4, 5, 5, 5];  
const uniqueArr = removeDuplicates(arr);  
console.log(uniqueArr); // 输出: [1, 2, 3, 4, 5]

3.使用reduce()方法

reduce()方法可以将数组元素组合成一个新值,我们可以利用它来创建一个没有重复元素的数组。

javascript 复制代码
function removeDuplicates(array) {  
    return array.reduce((accumulator, current) => {  
        if (!accumulator.includes(current)) {  
            accumulator.push(current);  
        }  
        return accumulator;  
    }, []);  
}  
  
const arr = [1, 2, 2, 3, 4, 4, 5, 5, 5];  
const uniqueArr = removeDuplicates(arr);  
console.log(uniqueArr); // 输出: [1, 2, 3, 4, 5]

4.使用Map数据结构

Map对象允许你存储键值对,并且键是唯一的。我们可以利用这个特性去除重复元素。

javascript 复制代码
function removeDuplicates(array) {  
    const map = new Map();  
    array.forEach(item => map.set(item, true));  
    return Array.from(map.keys());  
}  
  
const arr = [1, 2, 2, 3, 4, 4, 5, 5, 5];  
const uniqueArr = removeDuplicates(arr);  
console.log(uniqueArr); // 输出: [1, 2, 3, 4, 5]

5.使用两层循环

这种方法通过两层循环来比较和删除重复的元素,虽然效率不如前面提到的方法,但在一些简单的场景下仍然可以使用。

javascript 复制代码
function removeDuplicates(array) {  
    for (let i = 0; i < array.length; i++) {  
        for (let j = i + 1; j < array.length; j++) {  
            if (array[i] === array[j]) {  
                array.splice(j, 1);  
                j--; // 因为删除了一个元素,所以索引需要回退一位  
            }  
        }  
    }  
    return array;  
}  
  
const arr = [1, 2, 2, 3, 4, 4, 5, 5, 5];  
const uniqueArr = removeDuplicates(arr);  
console.log(uniqueArr); // 输出: [1, 2, 3, 4, 5]

每种方法都有其优缺点,你可以根据具体的场景和需求选择最适合的方法。在性能敏感的场景下,使用Set或Map通常会比使用循环更高效。


拓展一下🤷‍♀️

  • indexOf()

indexOf() 是 JavaScript 数组(Array)对象的一个方法,它用于返回在数组中可以找到给定元素的第一个索引,如果不存在,则返回 -1。

这个方法接受两个参数:

searchElement(必需):要查找的元素。
fromIndex(可选):开始查找的位置。如果该索引值大于或等于数组长度,则返回 -1,即数组不会被搜索。如果为负值,则将其作为从数组末尾开始的偏移量。即使该值为负数,它仍然从前往后搜索。如果省略该参数,则整个数组都会被搜索。

下面是一个使用 indexOf() 方法的例子:

javascript 复制代码
const array = [2, 5, 9, 1];  
  
const index = array.indexOf(9);  
console.log(index); // 输出: 2  
  
const notFoundIndex = array.indexOf(3);  
console.log(notFoundIndex); // 输出: -1  
  
const fromIndexIndex = array.indexOf(2, 3);  
console.log(fromIndexIndex); // 输出: -1(因为从索引 3 开始查找,数组中没有更多的 2)
  • reduce()

reduce() 是 JavaScript 数组(Array)对象的一个方法,它接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。

reduce() 方法的基本语法如下:

javascript 复制代码
array.reduce(function(accumulator, currentValue, currentIndex, array) {  
    // 返回累加器积累的结果  
}, initialValue);

参数说明

function(accumulator, currentValue, currentIndex, array): 执行数组中每个元素调用的函数,它包含四个参数。
accumulator(必需):累积器,累积回调函数的返回值;它是上一次调用回调时返回的累积值,或者是initialValue(如果提供了的话)。
currentValue(必需):数组中正在处理的当前元素。

currentIndex(可选):数组中正在处理的当前元素的索引。如果提供了initialValue,则索引为0,否则从索引1起始。

array(可选):调用reduce()的数组。

initialValue(可选):作为第一次调用callback函数时的第一个参数的值。如果没有提供初始值,则将使用数组中的第一个元素。在没有初始值的空数组上调用reduce将报错。

reduce() 方法非常适合将数组元素组合成单个输出值,比如求和、求积或者将数组对象合并为单一对象。

以下是一些使用 reduce() 方法的例子:

求和

javascript 复制代码
const numbers = [1, 2, 3, 4, 5];  
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);  
console.log(sum); // 输出: 15

数组元素去重:

javascript 复制代码
const array = [1, 2, 2, 3, 4, 4, 5];  
const uniqueArray = array.reduce((accumulator, currentValue) => {  
  if (!accumulator.includes(currentValue)) {  
    accumulator.push(currentValue);  
  }  
  return accumulator;  
}, []);  
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]

将多维数组转换为一维数组:

javascript 复制代码
const nestedArray = [1, [2, 3], [4, [5, 6]]];  
const flattenedArray = nestedArray.reduce((accumulator, currentValue) => {  
  return accumulator.concat(Array.isArray(currentValue) ? currentValue.reduce((a, b) => a.concat(b), []) : accumulator.concat(currentValue));  
}, []);  
console.log(flattenedArray); // 输出 [1, 2, 3, 4, 5, 6]

计算数组中每个元素出现的次数:

javascript 复制代码
const votes = ["vue", "react", "angular", "vue", "react", "angular", "vue", "react", "vue"];  
const count = votes.reduce((accumulator, currentValue) => {  
  if (!accumulator[currentValue]) {  
    accumulator[currentValue] = 1;  
  } else {  
    accumulator[currentValue]++;  
  }  
  return accumulator;  
}, {});  
console.log(count); // 输出 { vue: 4, react: 3, angular: 2 }

对象属性的累加:

javascript 复制代码
const items = [  
  { name: 'item1', price: 10 },  
  { name: 'item2', price: 20 },  
  { name: 'item3', price: 30 }  
];  
const totalPrice = items.reduce((accumulator, currentValue) => accumulator + currentValue.price, 0);  
console.log(totalPrice); // 输出 60

字符串连接:

虽然这可以用 join() 方法更简单地完成,但 reduce() 也可以用来连接数组中的字符串元素。

javascript 复制代码
const words = ['Hello', 'world', '!'];  
const sentence = words.reduce((accumulator, currentValue) => accumulator + ' ' + currentValue);  
console.log(sentence); // 输出 "Hello world !"

这些只是 reduce() 方法的一些应用场景示例。实际上,由于 reduce() 的灵活性,它可以用于任何需要累积或缩减数组元素的场景。

相关推荐
xiaofeichaichai4 小时前
Webpack
前端·webpack·node.js
问心无愧05135 小时前
ctf show web入门111
android·前端·笔记
唐某人丶5 小时前
模型越来越强,我们还需要 Agent 工程吗?—— 从价值重估到 Harness 实践
前端·agent·ai编程
智码看视界5 小时前
现代Web开发基础:全栈工程师的起航点
前端·后端·c5全栈
JS菌5 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
excel6 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia3117 小时前
https连接传输流程
前端·面试
徐小夕7 小时前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github
梦梦代码精7 小时前
2026年PHP开源商城系统实测对比:架构、多商户、商用授权,谁才是真·省心?
vue.js·docker·架构·开源·代码规范