gpt4 book ai didi

javascript - 如何在 JavaScript 中删除字符串中的重复单词?

转载 作者:行者123 更新时间:2023-12-02 21:46:10 25 4
gpt4 key购买 nike

我一直在尝试从字符串中删除重复的单词,但它不起作用。

我有当前的字符串:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com