作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一直在尝试从字符串中删除重复的单词,但它不起作用。
我有当前的字符串:
const categories = 'mexican, restaurant, mexican, food, restaurant'
我想要这个结果:
const x = 'mexican restaurant food'
我尝试过以下方法:
const x = categories.replace(/,/g, '');
const uniqueList = x
.split()
.filter((currentItem, i, allItems) => {
return i === allItems.indexOf(currentItem);
})
.join();
这给了我:
uniqueList = 'chinese restaurant chinese food restaurant'
上面的代码有什么问题吗?
最佳答案
我喜欢使用Set
为了这种目的。阅读文档:
The Set object lets you store unique values of any type, whether primitive values or object references.
这对你有用:
const categories = 'mexican, restaurant, mexican, food, restaurant'.split(', ');
const unique = Array.from(new Set(categories));
console.log(unique);
console.log(unique.join(' '));
希望对您有所帮助!
关于javascript - 如何在 JavaScript 中删除字符串中的重复单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60243102/
我是一名优秀的程序员,十分优秀!