How to remove duplicates from JavaScript array

How to remove duplicates from JavaScript array:

 

1. Creating new array and for loop

For loop and the new array would be the oldest possible solution. A solution you would use before array functions. Today you would do it this way.

const numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];

const newNumbers = [];

for(let i = 0; i < numbers.length; i++) {
  if(newNumbers.indexOf(numbers[i]) < 0)
    newNumbers.push(numbers[i])
}

console.log(newNumbers);

2. Filter function

JavaScript arrays contain many different built-in functions, and a filter is one of them. This function takes one parameter, the filter function, which then has three parameters. The first one is the element you are testing, the second is its index, and the last one is the original array.

const numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];

const newNumbers =
  numbers.filter(
    (element, index, array) =>
      array.indexOf(element) === index
    )

console.log(newNumbers);

3. Using the Set object

Using a set is one of the more modern solutions. Sets are part of the ES6 version of JavaScript, and they are objects that do not contain duplicates. You can create a set object using the original array and then convert it back to the array.

const numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];

const newNumbers = Array.from(new Set(numbers));

console.log(newNumbers);

These are the three most common ways to remove duplicates from an array. But programming is creative, and I am sure there are many more. If you know of any, please write it in the comments.

from Tumblr https://generouspiratequeen.tumblr.com/post/642085623124066304

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s