Last active
November 4, 2018 22:00
-
-
Save gbhasha/7cb278c5250442f42dbfb024e493a789 to your computer and use it in GitHub Desktop.
4 ways to remove duplicates from an array
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
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