LoginSignup
1
1

More than 5 years have passed since last update.

JavaScript のオブジェクトリテラルで重複した要素を一つにまとめてリストを作る

Last updated at Posted at 2018-07-18

目的

オブジェクトリテラルのあるキーが重複している場合、重複した要素を除外してリストを作りたいと考えました。
それも for loop なしで。

対象のリスト

someKey value1
1 ...
2 ...
3 ...
3 ...
2 ...
2 ...
5 ...

変更後

someKey value1
1 ...
2 ...
3 ...
5 ...

実装

findIndex と filter で実現できました!

var list = [{someKey:1},{someKey:2},{someKey:3},{someKey:3},{someKey:2},{someKey:2},{someKey:5}];

list.filter((element, index, array) => index === array.findIndex((current) => current.someKey === element.someKey))
結果
[ { someKey: 1 }, { someKey: 2 }, { someKey: 3 }, { someKey: 5 } ]
1
1
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
1
1