diff --git a/README.md b/README.md index a5a91bb..4c95935 100644 --- a/README.md +++ b/README.md @@ -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)** @@ -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 diff --git a/lib/rules/rules.json b/lib/rules/rules.json index 0f1afee..ee7a9b4 100644 --- a/lib/rules/rules.json +++ b/lib/rules/rules.json @@ -262,6 +262,11 @@ "alternative": "[... new Set(arr)]", "ES6": true }, + "uniqBy": { + "compatible": true, + "alternative": "Example of native implementation: https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_uniqBy", + "ES6": true + }, "replace": { "compatible": true, "alternative": "String.prototype.replace()" diff --git a/tests/unit/all.js b/tests/unit/all.js index abdb8ed..613865e 100644 --- a/tests/unit/all.js +++ b/tests/unit/all.js @@ -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() : '';