diff --git a/snippets/unique-values-of-array.md b/snippets/unique-values-of-array.md index d00c7f112..bbbaddbb9 100644 --- a/snippets/unique-values-of-array.md +++ b/snippets/unique-values-of-array.md @@ -1,13 +1,19 @@ ### Unique values of array -Use `reduce()` to accumulate all unique values in an array. -Check if each value has already been added, using `indexOf()` on the accumulator array. +use ES6 `Set` and the `...rest` operator to discard all duplicated values. ```js -var uniqueValues = arr => - arr.reduce( (acc, val) => { - if(acc.indexOf(val) === -1) - acc.push(val); - return acc; - }, []); +const unique = c => [...new Set(c)] +// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5] ``` + +Use `Array.filter` for an array containing only the unique values + +```js +const unique = c => c.filter(i => c.indexOf(i) === c.lastIndexOf(i)) +// unique([1,2,2,3,4,4,5]) -> [1,3,5] +``` + + + +