We will see what all ways can we remove duplicates from an array, starting off with the most obvious approach and gradually moving towards different ways.
You have
const arr = [1,2,4,3,1,1,4]
- The not so elegant way
And you want to remove the duplicates. The most basic approach will be
let final = [];
for(let i of arr) {
if(final.indexOf(i) === -1){
final.push(i);
}
}
2. Using map
You can always replace the iteration with map. But this does not change much.
let final = [];
arr.map((c) => {
if(final.indexOf(c) === -1) {
final.push(c);
}
})
3. Using filter
Using filter does make things look a little clean.
let final = arr.filter((cur,index) => arr.indexOf(cur) == index)
4. Using set
But nothing beats a set.
let final = [...new Set(arr)]