uniq
在 JavaScript 中通常指的是一个用于去除数组中重复元素的方法或函数。虽然 JavaScript 原生数组并没有内置 uniq
方法,但我们可以通过多种方式实现数组去重,或者使用一些库提供的 uniq
函数。
以下是一些实现数组去重的方法:
ES6 引入了 Set
对象,它类似于数组,但是成员的值都是唯一的,没有重复的值。可以利用这个特性来去重。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]
可以通过 filter
方法结合 indexOf
来实现去重。
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // [1, 2, 3, 4, 5]
reduce
方法也可以用来去重。
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]
如果你使用 lodash 库,可以直接调用其 uniq
函数来去重。
const _ = require('lodash');
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = _.uniq(array);
console.log(uniqueArray); // [1, 2, 3, 4, 5]
Set
或 lodash 的 uniq
方法可以非常简洁地实现去重。Set
方法在大多数情况下性能较好,因为它是基于哈希表的,查找和插入操作的时间复杂度接近 O(1)。Set
或 filter
结合 indexOf
的方法代码可读性较好,易于理解。数组去重在很多场景下都很有用,例如:
Set
,或者分批处理数据。例如,使用 lodash 的 uniqBy
函数可以根据对象的某个属性去重:
const _ = require('lodash');
const array = [{ id: 1 }, { id: 2 }, { id: 1 }];
const uniqueArray = _.uniqBy(array, 'id');
console.log(uniqueArray); // [{ id: 1 }, { id: 2 }]
这样可以确保根据对象的 id
属性去重。
领取专属 10元无门槛券
手把手带您无忧上云