1
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 3 years have passed since last update.

TypeScriptでArray<T>から重複要素を排除してユニークにする

Last updated at Posted at 2020-09-23

[JavaScriptでArrayをuniqにする]
(https://qiita.com/oubakiou/items/b848434e65d0644e1dfc)を元に

const defaultComparator = <T>(a: T, b: T): boolean => a === b

export const distinctBy = <T>(
  array: Array<T>,
  comparator: (a: T, b: T) => boolean = defaultComparator
): Array<T> =>
  array.filter(
    (elem, index, self) => self.findIndex(e => comparator(elem, e)) === index
  )

type Dog = {
  id: string
  name: string
}
const comparator = (a: Dog, b: Dog) => a.id === b.id
const dogsDistinct = (dogs: Array<Dog>) => distinctBy(dogs, comparator)

みたいな。

ところでJavascriptにはビルトインの等価性アルゴリズムが4種類ある(演算子としては3種類ある)のでcomparatorを実装する時はどれに合わせるのか気をつけたほうが良いと思います。

[1, 2] == '1,2' //true
[1, 2] === '1,2' //false
Object.is([1, 2], '1,2') //false

NaN == NaN //false
NaN === NaN //false
Object.is(NaN, NaN) //true

+0 == -0 //true
+0 === -0 //true
Object.is(+0, -0) //false

TypeScriptを使っていると型の上でも馴染みが深い、構造が一致するかどうかという比較はビルトインでは提供されていないため、必要であればdeep-equalのような外部パッケージを利用すると便利です。

see also

1
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
1
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?