35
33

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.

【Javascript】配列の要素がObjectのkey重複を削除

Posted at

動機

Javascriptの勉強のため。
mapに入れたりfor文で回す手もあるだろうけど、
Array.prototype.filter()Array.prototype.findIndex()が流行り(自分の中で)なのでやってみた。

コード

//キー重複のあるリスト
dupList =[
  { key: 'a', data: 'Alice'},
  { key: 'a', data: 'Antonio'},
  { key: 'a', data: 'Amanda'},
  { key: 'b', data: 'Bob'  },
  { key: 'c', data: 'Chris'},
  { key: 'c', data: 'Cindy'},
];

//重複削除
var cleanList = dupList.filter(function(v1,i1,a1){ 
  return (a1.findIndex(function(v2){ 
    return (v1.key===v2.key) 
  }) === i1);
});

//確認
console.log(cleanList);
// [ { key: 'a', data: 'Alice' },
//   { key: 'b', data: 'Bob' },
//   { key: 'c', data: 'Chris' } ]

findIndexで引き当てたキーのインデックスとフィルタ中のインデックスが一致すば残し、それ以外は除外する。

上記コードは前方が優先だけれども、後方を優先したい場合はfindIndex()の代わりにArray.prototype.lastIndexOf()を使ってで書けば良さそう。

node.jsで動作確認しました。

ご参考までに。

35
33
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
35
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?