Skip to content

Instantly share code, notes, and snippets.

@khalilst
Created August 21, 2020 19:24
Show Gist options
  • Save khalilst/77f9518784e5d34867c8fa3e33d8fc74 to your computer and use it in GitHub Desktop.
Save khalilst/77f9518784e5d34867c8fa3e33d8fc74 to your computer and use it in GitHub Desktop.
How to remove repetitive items from an array
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);
@khalilst
Copy link
Author

I have the idea for the three first approaches from Ali Rajabi's post here. But the last approach was my own idea.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment