假设我们有以下重复元素的数组
const originalArray = [1, 2, 2, 3, 4, 4, 5, 5];
一、使用Set(ES6方法):
ES6中的Set对象是一种特殊的集合数据结构,它只包含唯一的值,可以用于数组去重
const uniqueArray = [...new Set(originalArray)];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
二、使用filter方法:
使用Array的filter方法,对数组进行迭代,并返回一个新数组,其中包含满足特定条件的元素
const uniqueArray = originalArray.filter((item, index) => originalArray.indexOf(item) === index);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
三、使用reduce方法:
reduce方法允许我们将数组简化为一个值,我们可以使用它来构建一个不包含重复元素的新数组
const uniqueArray = originalArray.reduce((accumulator, currentValue) => {
if (!accumulator.includes(currentValue)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
四、使用for循环:
通过使用for循环,我们可以手动构建一个新数组,跳过已经存在的元素
const uniqueArray = [];
for (let i = 0; i < originalArray.length; i++) {
if (!uniqueArray.includes(originalArray[i])) {
uniqueArray.push(originalArray[i]);
}
}
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
五、使用Map数据结构:
Map也是一种可以用于数组去重的数据结构。通过遍历原始数组并将元素添加到Map中,由于Map的键是唯一的,重复元素将被自动去重。
const uniqueArray = [...new Map(originalArray.map(item => [item, item])).values()];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
六、使用includes方法与扩展运算符:
使用includes方法来判断新数组是否已经包含当前元素,如果不包含就将其添加到新数组中。
const uniqueArray = [];
for (const item of originalArray) {
if (!uniqueArray.includes(item)) {
uniqueArray.push(item);
}
}
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
七、使用Object键值对:
利用对象的键是唯一的特性,可以通过遍历原始数组,并将元素作为键添加到对象中,最后提取对象的键生成不含重复元素的数组。
const uniqueArray = Object.keys(originalArray.reduce((obj, item) => {
obj[item] = true;
return obj;
}, {}));
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
八、使用indexOf和lastIndexOf方法:
这是一种结合使用indexOf和lastIndexOf方法的简单方法。利用这两个方法来检查元素在数组中的首次和最后一次出现的索引是否相同,从而判断是否为重复元素。
const uniqueArray = originalArray.filter((item, index) => originalArray.indexOf(item) === index && originalArray.lastIndexOf(item) === index);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]