数组去重的几种方法:
(1)使用使用Set(Set对象只存储唯一值) [...new Set(array)]
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]
(2)使用indexOf和filter(遍历检查数组通过索引去重)
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]
(3)使用reduce方法(创建新数组,不包含重复数组)
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.reduce((acc, curr) => {
if (acc.indexOf(curr) === -1) {
acc.push(curr);
}
return acc;
}, []);
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]
(4)使用Map
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = Array.from(new Map(array.map(item => [item, item])).values());
console.log(uniqueArray); // 输出 [1, 2, 3, 4, 5]