我有2个字符串数组。第二个数组列出了“用过的单词”。我正在尝试从第一个数组中删除除第二个数组项的第一次出现以外的所有内容。代码可以正常工作,但无法删除最后2个重复项。
第一个数组StoryWords = ['really','very','basally','really','very','basically','really','very','basically','really','very ','基本上','真正','非常','基本上”,“更多”,“更多”,“更多”]]
第二个数组overusedWords = ['really','very','basically'];
预期输出:['真的','非常','基本','更多','更多','更多']
实际输出:['really','very','basically','really','very','basically','more','more','more']
const storyWords = ['really', 'very', 'basically','really', 'very', 'basically','really', 'very', 'basically','really', 'very', 'basically','really', 'very', 'basically',"more","more","more"];
let overusedWords = ['really', 'very', 'basically'];
overusedWords.forEach(f=>{
storyWords.forEach((s,i)=>{
if(s === f){
if(storyWords.indexOf(s) !== storyWords.lastIndexOf(s)){ // using i in exchange of i results same
storyWords.splice(storyWords.lastIndexOf(s),1);
}
}
})
})
console.log(storyWords);
预期输出:['真的','非常','基本','更多','更多','更多']
实际输出:['really','very','basically','really','very','basically','more','more','more']
答案 0 :(得分:0)
您可以使用reduce来实现。我正在检查两种情况。 它不在输出数组中,也不在过度使用的单词中
var storyWords = ['really', 'very', 'basically','really', 'very', 'basically','really', 'very', 'basically','really', 'very', 'basically','really', 'very', 'basically',"more"]
var overusedWords = ['really', 'very', 'basically'];
var output = storyWords.reduce((filterWords, word) => (!filterWords.includes(word) || !overusedWords.includes(word)) ? filterWords.concat(word) : filterWords,[])
console.log(output)