Merge pull request #7 from prodigic/master
Update unique-values-of-array.md
This commit is contained in:
@ -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]
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user