docs: Add example showing how to use uniqBy with object arrays (#410)
Some checks are pending
CI / codecov (push) Waiting to run
Release / release (push) Waiting to run

* Add example showing how to use uniqBy with object arrays

* Add uniqBy example with objects to other docs

* Apply suggestions from code review

* Update src/array/uniqBy.ts

---------

Co-authored-by: Sojin Park <raon0211@gmail.com>
This commit is contained in:
spookyuser 2024-08-28 16:23:16 +02:00 committed by GitHub
parent d47603f4cc
commit 984a072ff4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 41 additions and 0 deletions

View File

@ -23,3 +23,13 @@ function uniqBy<T, U>(arr: T[], mapper: (item: T) => U): T[];
uniqBy([1.2, 1.5, 2.1, 3.2, 5.7, 5.3, 7.19], Math.floor); uniqBy([1.2, 1.5, 2.1, 3.2, 5.7, 5.3, 7.19], Math.floor);
// [1.2, 2.1, 3.2, 5.7, 7.19] // [1.2, 2.1, 3.2, 5.7, 7.19]
``` ```
```typescript
const array = [
{ category: 'fruit', name: 'apple' },
{ category: 'fruit', name: 'banana' },
{ category: 'vegetable', name: 'carrot' },
];
uniqBy(array, item => item.category).length
// 2
```

View File

@ -23,3 +23,14 @@ function uniqBy<T, U>(arr: T[], mapper: (item: T) => U): T[];
uniqBy([1.2, 1.5, 2.1, 3.2, 5.7, 5.3, 7.19], Math.floor); uniqBy([1.2, 1.5, 2.1, 3.2, 5.7, 5.3, 7.19], Math.floor);
// [1.2, 2.1, 3.2, 5.7, 7.19] // [1.2, 2.1, 3.2, 5.7, 7.19]
``` ```
```typescript
const array = [
{ category: 'fruit', name: 'apple' },
{ category: 'fruit', name: 'banana' },
{ category: 'vegetable', name: 'carrot' },
];
uniqBy(array, item => item.category).length
// 2
```

View File

@ -23,3 +23,13 @@ function uniqBy<T, U>(arr: T[], mapper: (item: T) => U): T[];
uniqBy([1.2, 1.5, 2.1, 3.2, 5.7, 5.3, 7.19], Math.floor); uniqBy([1.2, 1.5, 2.1, 3.2, 5.7, 5.3, 7.19], Math.floor);
// [1.2, 2.1, 3.3, 5.7, 7.19] // [1.2, 2.1, 3.3, 5.7, 7.19]
``` ```
```typescript
const array = [
{ category: 'fruit', name: 'apple' },
{ category: 'fruit', name: 'banana' },
{ category: 'vegetable', name: 'carrot' },
];
uniqBy(array, item => item.category).length
// 2
```

View File

@ -13,6 +13,16 @@
* uniqBy([1.2, 1.5, 2.1, 3.2, 5.7, 5.3, 7.19], Math.floor); * uniqBy([1.2, 1.5, 2.1, 3.2, 5.7, 5.3, 7.19], Math.floor);
* // [1.2, 2.1, 3.2, 5.7, 7.19] * // [1.2, 2.1, 3.2, 5.7, 7.19]
* ``` * ```
*
* @example
* const array = [
* { category: 'fruit', name: 'apple' },
* { category: 'fruit', name: 'banana' },
* { category: 'vegetable', name: 'carrot' },
* ];
* uniqBy(array, item => item.category).length
* // 2
* ```
*/ */
export function uniqBy<T, U>(arr: readonly T[], mapper: (item: T) => U): T[] { export function uniqBy<T, U>(arr: readonly T[], mapper: (item: T) => U): T[] {
const map = new Map<U, T>(); const map = new Map<U, T>();