From 03ee6f73ca30fabd4f12819df7aea14a0ada3151 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Wed, 18 Jul 2018 20:49:07 +0300 Subject: [PATCH] add uniqueElements By and ByRight --- snippets/filterNonUniqueBy.md | 4 ++-- snippets/uniqueElementsBy.md | 27 +++++++++++++++++++++++++++ snippets/uniqueElementsByRight.md | 27 +++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 snippets/uniqueElementsBy.md create mode 100644 snippets/uniqueElementsByRight.md diff --git a/snippets/filterNonUniqueBy.md b/snippets/filterNonUniqueBy.md index 4fa5a11c0..a2abdfe6a 100644 --- a/snippets/filterNonUniqueBy.md +++ b/snippets/filterNonUniqueBy.md @@ -19,6 +19,6 @@ filterNonUniqueBy( { id: 1, value: 'd' }, { id: 0, value: 'e' }, ], - (a, b) => a.id != b.id -); // [{id: 2, value: 'c'}] + (a, b) => a.id == b.id +); // [ { id: 2, value: 'c' } ] ``` diff --git a/snippets/uniqueElementsBy.md b/snippets/uniqueElementsBy.md new file mode 100644 index 000000000..08bf7b19a --- /dev/null +++ b/snippets/uniqueElementsBy.md @@ -0,0 +1,27 @@ +### uniqueElementsBy + +Returns all unique values of an array, based on a provided comparator function. + +Use `Array.reduce()` and `Array.some()` for an array containing only the first unique occurence of each value, based on the comparator function, `fn`. +The comparator function takes two arguments: the values of the two elements being compared. + +```js +const uniqueElementsBy = (arr, fn) => + arr.reduce((acc, v) => { + if (!acc.some(x => fn(v, x))) acc.push(v); + return acc; + }, []); +``` + +```js +uniqueElementsBy( + [ + { id: 0, value: 'a' }, + { id: 1, value: 'b' }, + { id: 2, value: 'c' }, + { id: 1, value: 'd' }, + { id: 0, value: 'e' }, + ], + (a, b) => a.id == b.id +); // [ { id: 0, value: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ] +``` diff --git a/snippets/uniqueElementsByRight.md b/snippets/uniqueElementsByRight.md new file mode 100644 index 000000000..42b351438 --- /dev/null +++ b/snippets/uniqueElementsByRight.md @@ -0,0 +1,27 @@ +### uniqueElementsByRight + +Returns all unique values of an array, based on a provided comparator function. + +Use `Array.reduce()` and `Array.some()` for an array containing only the last unique occurence of each value, based on the comparator function, `fn`. +The comparator function takes two arguments: the values of the two elements being compared. + +```js +const uniqueElementsByRight = (arr, fn) => + arr.reduce((acc, v) => { + if (!acc.some(x => fn(v, x))) acc.push(v); + return acc; + }, []); +``` + +```js +uniqueElementsByRight( + [ + { id: 0, value: 'a' }, + { id: 1, value: 'b' }, + { id: 2, value: 'c' }, + { id: 1, value: 'd' }, + { id: 0, value: 'e' }, + ], + (a, b) => a.id == b.id +); // [ { id: 0, value: 'e' }, { id: 1, value: 'd' }, { id: 2, value: 'c' } ] +```