javascript中带过滤器的元素计数器
我有两个数组,需要返回带有元素和计数器的map对象。它几乎完成了,但我仍然停留在计数器上——对于计数器>1的元素,它总是“未定义”。有人能帮我吗javascript中带过滤器的元素计数器,javascript,Javascript,我有两个数组,需要返回带有元素和计数器的map对象。它几乎完成了,但我仍然停留在计数器上——对于计数器>1的元素,它总是“未定义”。有人能帮我吗 const stopWords = ['', 'a', 'the', 'and', 'or']; const pageWords = ['HellO', 's', 'And', 'hellO', '', 'AnD', 'NAME', 'oR', 'apple', 'HELLO', 'aPple']; const wordsCount = (words
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','NAME','oR','apple','HellO','apple'];
const wordscont=(单词,停止单词)=>{
const all=新映射();
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;
全部。设置(字、计数);
返回acc;
}, {});
全部归还;
};
console.log(Array.from(wordscont(pageWords,stopWords)))