Update unique-values-of-array.md

This commit is contained in:
Xavey Aguarez
2017-12-11 16:46:07 -08:00
committed by GitHub
parent e5562f2674
commit 18c14a236a

View File

@ -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]
```