Created
October 1, 2017 08:05
-
-
Save tkssharma/bd2ae3d7a9644275195e4e306f280b6d to your computer and use it in GitHub Desktop.
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
Removing duplicates of an array and returning an array of only unique elements | |
// ES6 Implementation | |
var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8]; | |
Array.from(new Set(array)); // [1, 2, 3, 5, 9, 8] | |
// done with set in ES6 as it will not allow duplicates in array | |
// ES5 Implementation | |
var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8]; | |
uniqueArray(array); // [1, 2, 3, 5, 9, 8] | |
function uniqueArray(array) { | |
var hashmap = {}; | |
var unique = []; | |
for(var i = 0; i < array.length; i++) { | |
// If key returns undefined (unique), it is evaluated as false. | |
if(!hashmap.hasOwnProperty(array[i])) { | |
hashmap[array[i]] = 1; | |
unique.push(array[i]); | |
} | |
} | |
return unique; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment