返回
JS数组去重7大妙招,轻松解决重复元素难题!
前端
2024-02-18 01:25:06
JS数组去重的方式详细总结(7种)
前言
数组去重是在面试中经常遇到的问题,也是在日常开发中经常被使用的。本文将详细总结7种数组去重的方式,以便大家在实际应用中灵活运用。
例:将下面数组去除重复元素(以多种数据类型为例)
const arr = [1, 2, 3, 'a', 'b', 'a', true, true, {name: 'Tom'}, {name: 'Tom'}];
7种数组去重方式
1. 利用Set() + Array.from()
const set = new Set(arr);
const newArr = Array.from(set);
2. 利用indexOf() + filter()
const newArr = arr.filter((item, index) => arr.indexOf(item) === index);
3. 利用reduce()
const newArr = arr.reduce((acc, item) => {
if (!acc.includes(item)) {
acc.push(item);
}
return acc;
}, []);
4. 利用对象键值对
const obj = {};
const newArr = arr.filter(item => obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true));
5. 利用Array.prototype.unique()
if (!Array.prototype.unique) {
Array.prototype.unique = function() {
return this.filter((item, index) => this.indexOf(item) === index);
};
}
const newArr = arr.unique();
6. 利用ES6扩展运算符 + Set()
const newArr = [...new Set(arr)];
7. 利用lodash.uniq()
const newArr = _.uniq(arr);
对比分析
方式 | 时间复杂度 | 空间复杂度 | 兼容性 |
---|---|---|---|
Set() + Array.from() | O(n) | O(n) | IE9+ |
indexOf() + filter() | O(n^2) | O(n) | IE9+ |
reduce() | O(n^2) | O(n) | IE9+ |
对象键值对 | O(n) | O(n) | IE9+ |
Array.prototype.unique() | O(n^2) | O(1) | 所有现代浏览器 |
ES6扩展运算符 + Set() | O(n) | O(n) | 所有现代浏览器 |
lodash.uniq() | O(n) | O(n) | 需引入lodash库 |
注: 以上时间复杂度和空间复杂度分析仅供参考,具体性能表现会因浏览器和运行环境而异。
总结
以上7种数组去重方式各有优缺点,大家可以根据实际场景选择最合适的方案。在面试中,如果能灵活运用多种去重方式,会给考官留下深刻印象。
在实际开发中,数组去重是一种常用的操作,掌握这些方法可以有效提升代码效率和可读性。希望本文能为大家带来帮助!