JavaScript数组去重方法:Set和reduce函数
使用Set数据结构可以很方便地去重一个数组。
const arr = [1, 2, 2, 3, 3, 4, 5, 5];
const arr2 = [...new Set(arr)];
console.log(arr2); // [1, 2, 3, 4, 5]
另一种方法是使用reduce函数来对数组进行去重。
const arr = [1, 2, 2, 3, 3, 4, 5, 5];
const arr2 = arr.reduce((prev, cur) => prev.includes(cur) ? prev : [...prev, cur], []);
console.log(arr2); // [1, 2, 3, 4, 5]
这里使用了ES6的箭头函数,如果当前元素已经存在于前面的结果数组中,就直接返回前面的数组,否则将当前元素加入数组中。注意,这里使用了展开运算符'...'来将前面的数组展开,这样才能将当前元素加入数组中。最后,初始的结果数组是一个空数组。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/m84J 著作权归作者所有。请勿转载和采集!