How to remove duplicates in an array.

Dave GillickDave Gillick
3 min read

In today's posts, I will show you two methods on how to remove duplicates from an array.

In our first example, we will remove duplicates from our array using a Set.

The Set object lets you store unique values of any type, whether primitive values or object references Set objects are collections of values. A value in the Set may only occur once; it is unique in the Set's collection. Learn more

Let's start with creating our function uniqueArray. We will use arr as the function argument to pass an array into the function.

const uniqueArray = (arr) => {

};

Our function will return a new array.

const uniqueArray = (arr) => {
return [];

};

Next, we will pass in our array into a new Set and use a (...)spread to convert the Set back into an array.

const uniqueArray = (arr) => {
return [ new Set(arr)];

};

Convert our Set back into an array using a (...) spread.

const uniqueArray = (arr) => {
return [...new Set(arr)];

};

To test our function we will create an array of duplicates and check our result using console.log.

const arrayOfDuplicates = [1,2,1,3,4,5,4,6];

  const uniqueArray = (arr) => {
  return [...new Set(arr)];
};

console.log(uniqueArray(arrayOfDuplicates));

In our second example, we will use forEach().

The forEach() method executes a provided function once for each array element.

We'll create our function and create a new array result inside our function.

//forEach method

const uniqueArray = arr => {
  consts result = [];

}

Next, we will use the forEach Method on the array passed into the function.

The forEach() method will execute a function once for each array element (item). Using a conditional statement, if the results array does not include the item, then the item will be pushed into the results array.

The include() method returns true if an element is in an array or false if it is not.

//forEach method 

const uniqueArray = arr => {
  result = [];
  arr.forEach(item => {
    if(!result.includes(item)){
      result.push(item)
    }
  })

}

To complete our function we will return results and use console.log to check the output of our function.

//forEach method 

const uniqueArray = arr => {
  result = [];
  arr.forEach(item => {
    if(!result.includes(item)){
      result.push(item);
    }
  })
  return result;
}

console.log(uniqueArray(numbers));

Note: Our functions above will only work with primitives and not objects or 2-dimensional arrays.

There are other ways that we can achieve this by combining reduce() map() and filter(). I will add a new post on how to do this shortly.

In the meantime, please feel free to share, comment and like my post.

Happy coding :-)

0
Subscribe to my newsletter

Read articles from Dave Gillick directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dave Gillick
Dave Gillick