Skip to content

Instantly share code, notes, and snippets.

@gbhasha
Last active November 4, 2018 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbhasha/7cb278c5250442f42dbfb024e493a789 to your computer and use it in GitHub Desktop.
Save gbhasha/7cb278c5250442f42dbfb024e493a789 to your computer and use it in GitHub Desktop.
4 ways to remove duplicates from an array
let a = [1,2,5,1,1,2,8];
// 1. Using for loop
let b = [];
let len = a.length;
for(let i=0; i<len; i++) {
if(b.indexOf(a[i]) === -1) {
b.push(a[i]);
}
}
console.log(b);
// 2. Using sort and remove
let c = [];
let _temp;
let len1 = a.length;
a.sort()
for(let i=0; i<len1; i++) {
if(_temp !== a[i]) {
c.push(a[i]);
_temp = a[i];
}
}
console.log(c);
// 3. using hash table (object)
let arr = [1,2,5,1,1,2,8];
let obj = {}
for (val of arr) {
obj[val] = parseInt(val);
}
console.log(Object.values(obj))
// 4. using hash table (ES6 set) - one line
console.log([... new Set(arr)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment