Skip to content

Instantly share code, notes, and snippets.

@tkssharma
Created October 1, 2017 08:05
Show Gist options
  • Save tkssharma/bd2ae3d7a9644275195e4e306f280b6d to your computer and use it in GitHub Desktop.
Save tkssharma/bd2ae3d7a9644275195e4e306f280b6d to your computer and use it in GitHub Desktop.
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