删除第二次出现的同名数组对象

remove the second occurrence of array object with same name

我有这个数组(java 脚本对象数组)

users=[{name:'arrow',age:50,id:444}
       {name:'bow',age:66,id:884}
       {name:'arrow',age:30,id:99},
       {name:'apple',age:50,id:999}
       {name:'bow',age:50,id:9669}]

我想删除第二次出现的同名,在这种情况下,我想删除 {name:'arrow',age:30,id:99} and {name:'bow',age:50,id:9669} 并保留第一次出现的 {name:'arrow',age:50,id:444} and {name:'bow',age:66,id:884}

结果数组应该是:

users=     [{name:'arrow',age:50,id:444}
           {name:'bow',age:66,id:884},
           {name:'apple',age:50,id:999}]
       
const users = [
    { name: 'arrow', age: 50, id: 444 },
    { name: 'bow', age: 66, id: 884 },
    { name: 'arrow', age: 30, id: 99 },
    { name: 'apple', age: 50, id: 999 },
    { name: 'bow', age: 50, id: 9669 }
]

const uniqueUsers = users.reduce((acc, user) => {
    if (!acc.find(u => u.name === user.name)) {
        acc.push(user)
    }
    return acc
}, [])

我会采用 array.filter 的方法:

function removeDuplicateKeyFromArray(arrayOfObjects,keyName){
  keyHolder = {}
  arrayOfObjects.filter((obj)=>{
      if(keyHolder[obj.keyName]){
         return false 
       }
      keyHolder[obj.keyName] = 1 //or true
      return true
    })
}

我会创建 2 个 for-loops,以过滤掉任何重复项。 这是我的代码:

let users = [{name:'arrow',age:50,id:444},
  {name:'bow',age:66,id:884},
  {name:'arrow',age:30,id:99},
  {name:'apple',age: 50,id: 990},
  {name:'bow',age: 50,id: 9669}]

for (let i = 0; i < users.length; i++) {
  for(let x = 0; i < users.length; i++) {
    if(users[i].name == users[x].name) {
      users.splice(users[x], 1)
    }
  }
}