js 去重数组
有几种方法可以在 JavaScript 中去重一个数组:
- 使用 Set 数据结构:Set 是 ES6 中引入的一种新的数据结构,它可以存储任意类型的唯一值。可以使用 Set 去重一个数组,然后将 Set 转换回数组。例如:
const array = [1, 2, 3, 4, 4, 5, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]
- 使用 filter 方法和 indexOf 方法:使用数组的 filter 方法和 indexOf 方法结合,可以创建一个新的数组,其中只包含原数组中的唯一值。例如:
const array = [1, 2, 3, 4, 4, 5, 5];
const uniqueArray = array.filter((value, index, self) => {
return self.indexOf(value) === index;
});
console.log(uniqueArray); // [1, 2, 3, 4, 5]
- 使用 reduce 方法:使用数组的 reduce 方法可以将一个数组转换为一个值。可以使用 reduce 方法和 indexOf 方法结合,创建一个新的数组,其中只包含原数组中的唯一值。例如:
const array = [1, 2, 3, 4, 4, 5, 5];
const uniqueArray = array.reduce((accumulator, value) => {
if (accumulator.indexOf(value) === -1) {
accumulator.push(value);
}
return accumulator;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4, 5]
以上是几种常见的方法,可以根据需要选择其中一种方法去重一个数组
原文地址: http://www.cveoy.top/t/topic/idd5 著作权归作者所有。请勿转载和采集!