Skip to content

Commit

Permalink
Add uniqBy
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexP11223 committed Oct 21, 2022
1 parent a7261a8 commit a32443e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ objects can easily be converted to an array by use of the
1. [_.some](#_some)
1. [_.sortBy](#_sortby-and-_orderby)
1. [_.uniq](#_uniq)
1. [_.uniqBy](#_uniqBy)
1. [_.uniqWith](#_uniqWith)

**[Function](#function)**
Expand Down Expand Up @@ -1808,6 +1809,33 @@ Produces a duplicate-free version of the array, using === to test object equalit

**[⬆ back to top](#quick-links)**

### _.uniqBy

Like `_.uniq` but compares the elements using the provided function or object key.

```js
// Lodash: _.uniqBy
// Underscore: _.uniq
_.uniqBy([2.1, 1.2, 2.3], Math.floor);
// => [2.1, 1.2]
_.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]

// Native
[...new Map([2.1, 1.2, 2.3].map(v => [Math.floor(v), v]).reverse()).values()];
// => [2.1, 1.2]
[...new Map([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }].map(o => [o.x, o]).reverse()).values()];
// => [{ 'x': 1 }, { 'x': 2 }]
```

#### Browser Support for Spread in array literals

![Chrome][chrome-image] | ![Edge][edge-image] | ![Firefox][firefox-image] | ![IE][ie-image] | ![Opera][opera-image] | ![Safari][safari-image]
:-: | :-: | :-: | :-: | :-: | :-: |
46.0 ✔ | 12.0 ✔ | 16.0 ✔ | ✖ | 37.0 ✔ | 8.0 ✔ |

**[⬆ back to top](#quick-links)**

## Function

### _.after
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/all.js
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,21 @@ describe('code snippet example', () => {
});
});

describe('uniqBy', () => {
function uniqBy(arr, iteratee) {
return [...new Map(arr.map(v => [typeof iteratee === 'function' ? iteratee(v) : v[iteratee], v]).reverse()).values()];
};

it('should take an iteratee function', () => {
assert.deepStrictEqual(_.uniqBy([2.1, 1.2, 2.3], Math.floor), uniqBy([2.1, 1.2, 2.3], Math.floor));
});

it('should take an object key', () => {
assert.deepStrictEqual(_.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'),
uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'));
});
});

describe('capitalize', () => {
function capitalize(string) {
return string ? string.charAt(0).toUpperCase() + string.slice(1).toLowerCase() : '';
Expand Down

0 comments on commit a32443e

Please sign in to comment.