Update unique-values-of-array.md
This commit is contained in:
@ -1,13 +1,19 @@
|
|||||||
### Unique values of array
|
### Unique values of array
|
||||||
|
|
||||||
Use `reduce()` to accumulate all unique values in an array.
|
use ES6 `Set` and the `...rest` operator to discard all duplicated values.
|
||||||
Check if each value has already been added, using `indexOf()` on the accumulator array.
|
|
||||||
|
|
||||||
```js
|
```js
|
||||||
var uniqueValues = arr =>
|
const unique = c => [...new Set(c)]
|
||||||
arr.reduce( (acc, val) => {
|
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||||
if(acc.indexOf(val) === -1)
|
|
||||||
acc.push(val);
|
|
||||||
return acc;
|
|
||||||
}, []);
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
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