Last active
August 29, 2015 14:07
-
-
Save hontas/4779ae1dcd1c72d28f4d to your computer and use it in GitHub Desktop.
Uniq implementation using Array.prototype.reduce
This file contains hidden or 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
/* more functional version using concat */ | |
function uniq(array) { | |
return array.reduce(function(result, currentElement) { | |
if (result.indexOf(currentElement) < 0) { | |
return results.concat([currentElement]); | |
} | |
return result; | |
}, []); | |
} | |
/* more traditional version using push */ | |
function uniq2(array) { | |
return array.reduce(function(result, currentElement) { | |
if (result.indexOf(currentElement) < 0) { | |
results.push(currentElement); | |
} | |
return result; | |
}, []); | |
} | |
/* using array.filter */ | |
function uniq3(array) { | |
return array.filter(function (value, index, self) { | |
return self.indexOf(value) === index; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment