有多种方法可以实现数组去重
- 使用Set
- 使用filter方法
- 使用reduce方法
- 使用for循环和indexOf方法
- 使用Map
- 使用includes方法
- 使用递归
1_使用Set
ES6中的Set对象是一种无重复值的有序列表。通过将数组转换为Set对象,可以去除重复的元素,然后再将Set对象转换回数组。
<script>
const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray);
</script>
2_使用filter方法
利用数组的filter方法,遍历数组并筛选出没有重复出现的元素。
const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = array.filter((value, index, self) => {
return self.indexOf(value) === index;
});
console.log(uniqueArray);
3_使用reduce方法
利用reduce方法,遍历数组并将不重复的元素添加到一个新数组中
const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = array.reduce((prev, curr) => {
if (!prev.includes(curr)) {
prev.push(curr);
}
return prev;
}, []);
console.log(uniqueArray);
4_使用for循环和indexOf方法
通过遍历数组,判断元素在之前的部分是否已经出现过,若没有出现过,则添加到新数组中。
const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = array.reduce((prev, curr) => {
if (!prev.includes(curr)) {
prev.push(curr);
}
return prev;
}, []);
console.log(uniqueArray);
5_使用Map
利用Map对象的键值对特性,遍历数组并将元素作为键存储到Map中,然后再将Map的键转换为数组。
const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = Array.from(new Map(array.map(item => [item, item])).values());
console.log(uniqueArray);
6_使用includes方法
通过遍历数组,利用includes方法判断元素是否已经在新数组中存在,若不存在则添加到新数组中。
const array = [1, 2, 3, 3, 4, 5, 5];
const uniqueArray = [];
for (let i = 0; i < array.length; i++) {
if (!uniqueArray.includes(array[i])) {
uniqueArray.push(array[i]);
}
}
console.log(uniqueArray);
7_使用递归
逐个遍历数组的元素,如果元素在后面的部分中还出现过,则跳过,直到遍历完所有元素。
const array = [1, 2, 3, 3, 4, 5, 5];
function unique(array) {
if (array.length === 1) {
return array;
}
const first = array[0];
const rest = unique(array.slice(1));
if (rest.includes(first)) {
return rest;
} else {
return [first, ...rest];
}
}
const uniqueArray = unique(array);
console.log(uniqueArray);
根据不同的场景和需求选择适合