Remove Array duplicates

As a JavaScript consultant, I meet with a lot of clients. In some cases, it’s like having a programmer’s job interview.

At one of this clients, I got a JavaScript test and one of the questions was to implement a removeDuplicates function that accepts an Array and return a new Array without duplicates.

This got me thinking on how many ways I can implement this.

1. Using Array.forEach

const removeDuplicates = arr => {
  const o = {};
  arr.forEach(item => o[item] = item);
  return Object.values(o);
};

2. Using Array.reduce

const removeDuplicates = arr => Object.values(
  arr.reduce((acc, item) => Object.assign(acc, { [item]: item }), {})
);

3. Using Array.reduce, Array.indexOf and Array.concat

const removeDuplicates = arr => arr.reduce(
  (acc, item) => !~acc.indexOf(item) ? acc.concat([item]) : acc, []
);

4. Using Array.filter and Array.find

const removeDuplicates = arr => arr.filter(
  (item, index) => !arr.slice(0, index).find(e => e === item)
);

5. Using Array.filter and Array.indexOf

const removeDuplicates = arr => arr.filter(
  (item, index) => arr.indexOf(item) === index
);

6. Using Set and spread

const removeDuplicates = arr => [...new Set(arr)];

Which one would you favour? If you have any more ideas, I would love to hear them.

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com