gpt4 book ai didi

javascript - javascript 中带有过滤器的元素计数器

转载 作者:行者123 更新时间:2023-12-02 22:06:38 24 4
gpt4 key购买 nike

我有两个数组,需要返回带有元素和计数器的 map 对象。它几乎完成了,但我卡在了 counter - 对于 counter>1 的元素,它总是“未定义”。谁能帮我吗?

const stopWords = ['', 'a', 'the', 'and', 'or'];
const pageWords = ['HellO', 's', 'And', 'hellO', '', 'AnD', 'NAME', 'oR', 'apple', 'HELLO', 'aPple'];

const wordsCount = (words, stopWords) => {
const all = new Map();
const arr = words.map(word => word.toLowerCase())
.filter(word => !stopWords.includes(word))
.reduce((acc, word) => {
const count = all.has(word) ? acc[word] + 1 : 1;
all.set(word, count);
return acc;
}, {});
return all;
};

//what I need: [['hello', 3], ['s', 1], ['name', 1], ['apple', 2]]

最佳答案

你们非常接近。我相信您现有代码的唯一问题是您如何访问单词的当前计数。您应该使用 all.get(word) 来访问现有计数,而不是使用 acc[word]。像这样:

const stopWords = ['', 'a', 'the', 'and', 'or'];
const pageWords = ['HellO', 's', 'And', 'hellO', '', 'AnD', 'NAME', 'oR', 'apple', 'HELLO', 'aPple'];

const wordsCount = (words, stopWords) => {
const all = new Map();
const arr = words.map(word => word.toLowerCase())
.filter(word => !stopWords.includes(word))
.reduce((acc, word) => {
const count = all.has(word) ? all.get(word) + 1 : 1;
all.set(word, count);
return acc;
}, {});
return all;
};

console.log(Array.from(wordsCount(pageWords, stopWords)))

此外,此更改意味着您不再需要 acc,因此我认为 forEach 可以代替 reduce 使代码变得有点更容易阅读。像这样:

const stopWords = ['', 'a', 'the', 'and', 'or'];
const pageWords = ['HellO', 's', 'And', 'hellO', '', 'AnD', 'NAME', 'oR', 'apple', 'HELLO', 'aPple'];

const wordsCount = (words, stopWords) => {
const all = new Map();
words.map(word => word.toLowerCase())
.filter(word => !stopWords.includes(word))
.forEach(word => {
const count = all.has(word) ? all.get(word) + 1 : 1;
all.set(word, count);
});

return all;
};

console.log(Array.from(wordsCount(pageWords, stopWords)));

关于javascript - javascript 中带有过滤器的元素计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59694218/

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