Created
August 21, 2020 19:24
-
-
Save khalilst/77f9518784e5d34867c8fa3e33d8fc74 to your computer and use it in GitHub Desktop.
How to remove repetitive items 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
var x = new Array(1000000).fill(0).map(item => Math.floor(Math.random()*10)); | |
console.time('1.Set'); | |
var setResult = Array.from(new Set(x)); | |
console.timeLog('1.Set'); | |
console.log(setResult); | |
console.time('2.Reduce'); | |
var reduceResult = x.reduce((acc, item) => { | |
if (acc.indexOf(item) === -1) { | |
acc.push(item); | |
} | |
return acc; | |
}, []); | |
console.timeLog('2.Reduce'); | |
console.log(reduceResult); | |
console.time('3.Filter'); | |
var filterResult = x.filter((item, index) => x.indexOf(item) === index); | |
console.timeLog('3.Filter'); | |
console.log(filterResult); | |
console.time('4.reducedObject'); | |
var reducedObject = x.reduce((acc, item) => { | |
acc[item] = item; | |
return acc; | |
}, {}); | |
var reducedObjectResult = Object.values(reducedObject); | |
console.timeLog('4.reducedObject'); | |
console.log(reducedObjectResult); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have the idea for the three first approaches from Ali Rajabi's post here. But the last approach was my own idea.