简体   繁体   English

如何删除对象数组中的重复项?

[英]How to remove duplicates in Array of objects?

I am trying to remove duplicates in Array of objects by using filter method in Javascript.我正在尝试使用 Javascript 中的过滤器方法删除对象数组中的重复项。 This is what I tried这是我尝试过的

const students = [
    {
        name: 'Mark',
        age: 21
    },
    {
        name: 'Williams',
        age: 27
    },
    {
        name: 'Mark',
        age: 21
    }
]

const newStudents = students.filter(function(currentValue,index,arr) {
    return students.indexOf(currentValue) === index
})

console.log(newStudents)

I assume that you are trying to filter with one of the fields in the object.我假设您正在尝试使用 object 中的字段之一进行过滤。 Then, you can filter like:然后,您可以像这样过滤:

students.filter(obj => obj.name === 'Mark')

or you can define a filter function like:或者你可以定义一个过滤器 function 像:

function filterStudentByAge(student) {
  if(student.age > 21) return true
  else false
}

students.filter(filterStudent)

Your question is not that much clear to what you want to filter您的问题对您要过滤的内容不太清楚

but let assume that for example you want filter the stunted who's age is less then 25但是假设例如您要过滤age is less then 25的发育不良的人

So simply you can do like below:因此,您可以简单地执行以下操作:

const newStudents = students.filter(function(s,index,arr) {
    return s.age>25;
})

console.log(newStudents)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM