LoginSignup
0
2

More than 5 years have passed since last update.

ES6 オブジェクトの配列を特定のキーでユニークにする

Posted at

オブジェクトの配列内で同じ値を持つオブジェクトのユニーク配列を作成する.
同じオブジェクトであることの判定は、findIndexでおこない、条件合致したはじめのオブジェクトがユニーク後に残される.

let arr = [
  { name: "Newton", age: 84, role: "Physicist" },
  { name: "Newton", age: 84, role: "Mathematician" },
  { name: "Newton", age: 84, role: "Economist" },
  { name: "Mozart", age: 35, role: "Musician" },
  { name: "Darwin", age: 73, role: "Biologist" },
  { name: "Newton", age: 84, role: "Alchemist" },
  { name: "Mozart", age: 35, role: "Composer" },
]

let uniqArr = arr.filter((obj, index, self)=>{
  let firstIndex = self.findIndex((x)=>{ return obj.name === x.name })
  return firstIndex === index
})

console.log(uniqArr)
// [
//   {
//     age: 84,
//     name: "Newton",
//     role: "Physicist",
//   },
//   {
//     age: 35,
//     name: "Mozart",
//     role: "Musician",
//   },
//   {
//     age: 73,
//     name: "Darwin",
//     role: "Biologist",
//   }
// ]
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2