5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

配列内のオブジェクトで同一のプロパティに対して同じ値を持つものを除外したい

Last updated at Posted at 2018-05-18

配列内のオブジェクトでそれぞれ重複する値を持つものを除外したいと思ったので、やり方を備忘録として残します。

js

let arr = [{id: 1}, {id: 2}, {id: 1}, {id: 3}, {id: 2}]

// id=1, id=2 がダブってるので重複を削除して下記のようにしたい
arr = [{id: 1}, {id: 2}, {id: 3}]

こんな感じでやれます。

js
arr = arr.filter((elm, index, selfArr) => {
  return index === selfArr.findIndex(s => {
    return s.id === elm.id
  })
})

findIndex と filter の説明

js
// callbackでtrueとなる "最初" のindex番号を返す
findIndex(callback(elm, index, selfArray)) 

// callbackでtrueとなる要素だけ(trueの要素全て)を返す
filter(callback(elm, index, selfArray))

// どちらもcallbackの使わない引数は省略化

短く書くとこうなります。

js
// 1行でも書ける
arr = arr.filter((elm, index, selfArr) => index === selfArr.findIndex(s => s.id === elm.id))

もっと良い案があればどなたか教えてください。

5
0
4

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
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?