Codementor Events

Remove Array Duplicates in Javascript

Published Jan 30, 2020Last updated Jul 27, 2020
Remove Array Duplicates in Javascript

I worked on a project recently consuming a 3rd party API which returned duplicates in some arrays returned and i needed to remove duplicates from them.

I deemed it wise to pen down how i resolved this issue just in case someone else comes across this issue.

Using Javascript SET function

The Set object lets you store unique values of any type, whether primitive values or object references.

All we need do is to initialize a new set and pass in the required array we need to remove duplicates from as shown below.

const array = ["ade", "kemi", "bose", "esther", "felele", "ade"];

const uniqeSet = new Set(array);

/* this by default returns back an object of the unique value passed in the array    * above which we can spread in an array.
*/

// Set {"ade", "kemi", "bose", "esther", "felele"}

const arrayResponse = [...uniqeSet];

// ["ade", "kemi", "bose", "esther", "felele"]

Alternatively you could also use Array.from() to convert your object to an array.

The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

Using Javascript FILTER Function

The filter() method creates an array filled with all array elements that pass a test (provided as a function).
What this means is that once the conditions set is passed, it would be included in the array.

The filter also allows you to pass in some other parameters such as the index parameter which returns the position of the array element.

for example.

const arrays = ["ade", "kemi", "bose", "esther", "felele", "ade"];

const uniqueArray = arrays.filter(
  (array, index) => arrays.indexOf(array) === index
); 
// ["ade", "kemi", "bose", "esther", "felele"]

Using Javascript Reduce Function

This approach requires us to reduce the elements of an array, then add up the results into a final array based on the reducer function passed.

for example.

const arrayData = ["ade", "kemi", "bose", "esther", "felele", "ade"];

const arrResponse = arrayData.reduce((uniqeValue, item) => 

uniqeValue.includes(item) ? uniqeValue : [...uniqeValue, item], []);

console.log(arrResponse)
// ["ade", "kemi", "bose", "esther", "felele"]

And we are done. Hope this helps.

Discover and read more posts from Sunny Edogbo
get started
post commentsBe the first to share your opinion
Show more replies