Skip to content

Instantly share code, notes, and snippets.

@therealklanni
Created March 29, 2014 04:30
Show Gist options
  • Save therealklanni/9848443 to your computer and use it in GitHub Desktop.
Save therealklanni/9848443 to your computer and use it in GitHub Desktop.
Get unique elements of an Array
// 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