如何对包含重复单词的数组去重?附示例代码
数组去重解决方案
方法1:ES6 Set(最简洁)
这是目前最简便的方式,利用Set自动去重的特性,再转成数组即可,还能保留原数组中元素第一次出现的顺序:
const array = ['dog','dog','dog','cat','cat', 'mouse','egg','egg']; const newArray = [...new Set(array)]; // 输出结果: ['dog','cat','mouse','egg']
方法2:filter + indexOf(实现你想要的索引对比逻辑)
你之前尝试用map没成功,是因为map会返回和原数组长度一致的新数组,没法直接过滤重复项。换用filter就能实现“只保留第一次出现的元素”的逻辑:
const array = ['dog','dog','dog','cat','cat', 'mouse','egg','egg']; const newArray = array.filter((word, index) => { // 仅当当前元素的首次出现索引等于当前遍历索引时才保留 return array.indexOf(word) === index; }); // 输出结果: ['dog','cat','mouse','egg']
方法3:reduce手动构建去重数组
如果需要更手动控制的逻辑,可以用reduce逐步累加不重复的元素:
const array = ['dog','dog','dog','cat','cat', 'mouse','egg','egg']; const newArray = array.reduce((result, currentWord) => { // 如果结果数组里没有当前单词,就添加进去 if (!result.includes(currentWord)) { result.push(currentWord); } return result; }, []); // 初始值为空数组 // 输出结果: ['dog','cat','mouse','egg']
内容的提问来源于stack exchange,提问作者שני עיני
相关产品推荐
相关产品推荐

