3
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.

JavaScriptでArray<Object>をuniqにする

Last updated at Posted at 2019-06-21
const images = [
 {url : 'hoge.jpg'},
 {url : 'hoge.jpg'},
 {url : 'fuga.jpg'},
];
const condition = (a, b) => a.url === b.url;
const uniqImages = images.filter(
  (elem, index, self) => self.findIndex(
    (e) => condition(elem, e)
  ) === index
);

console.log(uniqImages);

findIndexはindexOfと同様に最初に見つかった要素のindexを返すので、それ以外のindexをフィルターすると条件に対してユニークになる。

スクリーンショット 2019-06-21 19.48.20.png

via
https://qiita.com/piroor/items/02885998c9f76f45bfa0
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

3
0
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
3
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?