A javascript utility function to remove duplicates from a list

7 years ago
JavaScript
uniquify

There are many cases where when we are handling a list, for addition especially, we end up with a list with many duplciate values.Removing duplicate values is kind of trivial thing to do but perhaps it could be simpler when with a simple function call to do it. So I come up with something like this. Here it is;

function uniquify(list) {
 const l = []
 list.forEach(word=>{
  if (l.indexOf(word)<0) l.push(word)
 })
 return l
}

To call the function, we can use;

const numbers = [1,1,2,2,3,3]
console.log(uniquify(numbers))
// display [1, 2, 3]

So far this only works on numbers or strings. I have plan to make it work for objects too in the future.

Thanks for reading!