数组去掉重复值的常见做法有以下几种:
1.使用Set数据结构:创建一个空的Set,遍历数组,将每个元素添加到Set中,由于Set只能存储唯一的值,重复的值将自动被剔除。最后将Set转换为数组即可得到结果。
const array = [1, 2, 1, 3, 2]; const result = [...new Set(array)]; console.log(result); // [1, 2, 3]
2.使用Array.filter()方法:遍历数组,使用Array.filter()方法筛选出不包含重复值的新数组。
const array = [1, 2, 1, 3, 2]; const result = array.filter((value, index, self) => { return self.indexOf(value) === index; }); console.log(result); // [1, 2, 3]
3.使用Array.reduce()方法:遍历数组,使用Array.reduce()方法将数组中不重复的元素添加到一个新数组中。
const array = [1, 2, 1, 3, 2]; const result = array.reduce((accumulator, value) => { if (!accumulator.includes(value)) { accumulator.push(value); } return accumulator; }, []); console.log(result); // [1, 2, 3]
除了上述方法,还可以使用循环嵌套比较、使用indexOf()方法等方式实现数组去重。根据具体的需求和编程语言,选择最适合的方式即可。
版权申明:财旺号所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流,不声明或保证其内容的正确性,如发现本站有涉嫌抄袭侵权/违法违规的内容。请发送邮件至 1790309299@qq.com 举报,一经查实,本站将立刻删除。