从数组中删除出现多次的所有元素 [英] remove all elements that occur more than once from array

查看:79
本文介绍了从数组中删除出现多次的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在人们认为这与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"] */

Codepen演示

这篇关于从数组中删除出现多次的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆