从数组中删除出现多次的所有元素 [英] remove all elements that occur more than once from array
问题描述
在人们认为这与Stack Overflow上关于删除重复项的所有其他答案相同之前,您能否先看一下返回的内容而不是我想要做的事情.
Before people think this is the same as all these other answers on Stack Overflow regarding removing duplicates can you please look at what is returned as opposed to what I am looking to do.
我想删除所有出现多次的元素.我尝试了以下方法:
I want to remove all elements that occur more than once. I have tried the following:
const a = ['Ronaldo', 'Pele', 'Maradona', 'Messi', 'Pele'];
const uniqueArray = a.filter(function(item, pos) {
return a.indexOf(item) == pos;
})
console.log(uniqueArray)
我希望我的uniqueArray
是
['Ronaldo', 'Maradona', 'Messi'];
推荐答案
简而言之:如果元素的第一个出现位置(indexOf
)也是元素在数组中的最后位置,则保留该值( lastIndexOf
).
In short: keep the value if the position of the first occurrence of the element (indexOf
) is also the last position of the element in the array (lastIndexOf
).
如果索引不相等,则该值将重复,您可以将其丢弃.
If the indexes are not equals then the value is duplicated and you can discard it.
const a = ['Ronaldo', 'Pele', 'Maradona', 'Messi',
'Pele', 'Messi', 'Jair', 'Baggio', 'Messi',
'Seedorf'];
const uniqueArray = a.filter(function(item, pos) {
return a.lastIndexOf(item) == a.indexOf(item);
});
console.log(uniqueArray);
/* output: ["Ronaldo", "Maradona", "Jair", "Baggio", "Seedorf"] */
这篇关于从数组中删除出现多次的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!