Created
March 29, 2014 04:30
-
-
Save therealklanni/9848443 to your computer and use it in GitHub Desktop.
Get unique elements of an Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Another useful reducer | |
// | |
// Get unique values of a 1d array | |
function unique (a, b) { | |
if (a.indexOf(b) < 0) a.push(b) | |
return a | |
} | |
// Very simple use case | |
var arr = [1, 5, 7, 2, 2, 3, 3, 4, 5, 5, 52, 4, 1, 2, 9, 1, 3, 5] | |
// Reduce it | |
arr.reduce(unique, []) // <= note the [] param | |
// Produces: | |
[1, 5, 7, 2, 3, 4, 52, 9] | |
// This can also be easily accomplished with Array#filter, | |
// but I really like the elegance of this reduce approach |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment