JavaScript Remove Duplicates From Array

JavaScript Remove Duplicates From Array

In JavaScript, we use an array for storing data in sequence. But there are many cases where you often face problems with an array when it contains a duplicate element. Many times we have required only a single entry for an element. At that time, removing the duplicate array concepts is very useful to us. By good luck, Javascript provides many ways to remove duplicates from an array, which we discuss in this article.

On the other hand, If you’re wondering, “How does JavaScript remove duplicates from array?” The answer is simple. Removing duplicates from an array in JavaScript is relatively straightforward and can be achieved using a few different methods.  

We will explain all of the methods in the simplest way possible so that you have no confusion at the end of this blog. 

With the help of many methods, we can remove duplicates from an array.

Here, we will discuss the methods of the array that are used for removing duplicates in an array: the filter() method, the set() method, the reduce() method, and the indexOf() method.

Now, without delay, let’s start with us.

You can also take JavaScript assignment help to learn more about this programming language.

Different Methods By Which JavaScript Remove Duplicates From Array

1. Set () Methods

A set is a collection of value-defined objects. It stores unique values. Now, we can understand with the help of examples. The Set method is the easiest and most efficient way to get rid of duplicates in an array. When it creates a new set, it automatically gets rid of any duplicates.

Program

var array = ["Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Delaware","Connecticut","Florida"];

console.log("without removing duplicate value output is", (array));

var uniquearray = [...new Set(array)];

console.log("with removing duplicate value output is", (uniquearray));

Output

without removing duplicate value output is (8) [‘Connecticut’, ‘Delaware’, ‘Florida’, ‘Georgia’, ‘Hawaii’, ‘Delaware’, ‘Connecticut’, ‘Florida’]

with removing duplicate value output is (5) [‘Connecticut’, ‘Delaware’, ‘Florida’, ‘Georgia’, ‘Hawaii’]

Set() method Explanation in brief 

In this program, we have first of all created one array. After that, we pass the value of this array that is (‘Connecticut’, ‘Delaware’, ‘Florida’, ‘Georgia’, ‘Hawaii’, ‘Delaware’, ‘Connecticut’, ‘Florida’) after that we print the output of this array that is console.log(“without removing duplicate value output is,” (array)); after that, we can create a new array that name is uniquearray and pass the value in this with the help of spread operator of the new Set() array. Where New Set(arr) is a set containing all the values in an array in which duplicates are necessarily removed. The spread operator just converts this back into an array.

Finally, we print the output of unique values with the help of console.log(“with removing duplicate value output is”, (uniquearray));.

Also read: How To Call A Function In JavaScript

2. Filter() and indexOf () methods 

Filter()

Filter () method returns the elements of an array that meet the condition specified in a callback function. The filter method is also a simple and efficient way to remove duplicates, by checking the index of each element in the array and only keeping unique elements.

IndexOf()

Returns either -1 if a value is missing from the array or the index of the value’s first occurrence there. It is also a case-sensitive method.

Program

let arrays = ["Head","Mouth", "Face", "Shoulder","Ear","Neck", "Hair", "Mouth","Head",  "Ear","Shoulder","Forehead","Arm"];

console.log(arrays);

let uniquearray = arrays.filter((array, index) => {return arrays.indexOf(array) == index});

console.log(uniquearray);

 Output

(13) [‘Head’, ‘Mouth’, ‘Face’, ‘Shoulder’, ‘Ear’, ‘Neck’, ‘Hair’, ‘Mouth’, ‘Head’, ‘Ear’, ‘Shoulder’, ‘Forehead’, ‘Arm’]

(9) [‘Head’, ‘Mouth’, ‘Face’, ‘Shoulder’, ‘Ear’, ‘Neck’, ‘Hair’, ‘Forehead’, ‘Arm’]

 Filter() and indexOf () methods Explanation in brief 

In this program, first, we must create an array that arrays by passing their values. After that, we can print their output with the help of console.log. After that, we created a function whose name is uniquearray and then pass the arguments first we put the array name in which we remove duplicate values that are arrays after that put ‘.’ then use the filter method() and pass the value (that is an array)and index after that we return output with the help of indexOf () method we use arrays.indexOf(array) after that compare with == index.

Output

3. Reduce() method

The reduce() method is used to reduce the array’s elements and combine them into a final array.

Program

var arr = ["Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Delaware","Connecticut","Florida"];

    function removeDuplicates(arr) {

        var unique = arr.reduce(function (acc, curr) {

            if (!acc.includes(curr))

                acc.push(curr);

            return acc;

        }, []);

        return unique;

    }

    console.log(removeDuplicates(arr));

Output

(5) [‘Connecticut’, ‘Delaware’, ‘Florida’, ‘Georgia’, ‘Hawaii’]

Also read: JavaScript Exit Function

4. Reduce() method and Includes()

Reduce is always a little more difficult to grasp but performs a powerful reduction operation borrowed from functional programming. Based on a reducer function you give, the reduce() method is used to reduce the array’s elements and combine them into a final array. The includes() method returns true if an element is in an array and false otherwise.

Program

let names = ["Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Delaware","Connecticut","Florida"];

let uniquenames = names.reduce((result, subject) => {

    return result.includes(names) ? result : [...result, subject];

}, []);

console.log(uniquenames);

Output

(8) [‘Connecticut’, ‘Delaware’, ‘Florida’, ‘Georgia’, ‘Hawaii’, ‘Delaware’, ‘Connecticut’, ‘Florida’]

5. Push() method and indexOf () method

Push() method appends new elements to the end of an array and returns the new length of the array. And indexOf () method we have already explained on above.

Program

function getUnique(arr){

    let uniqueArr = [];

    for(let i of arr) {

        if(uniqueArr.indexOf(i) === -1) {

            uniqueArr.push(i);

        }

    }

    console.log(uniqueArr);

}

const array = ["Head","Mouth", "Face", "Shoulder","Ear","Neck", "Hair", "Mouth","Head",  "Ear","Shoulder","Forehead","Arm"];

getUnique(array);

The duplicate elements are removed from the array in the program mentioned above.

Here,

All the items of an arr array are looped through using the for…of loop.

If the element is not present in the array, the indexOf() function returns -1. 

As a result, on each iteration, if the element equals -1, push is used to add the element to uniqueArr ().

Output

(9) [‘Head’, ‘Mouth’, ‘Face’, ‘Shoulder’, ‘Ear’, ‘Neck’, ‘Hair’, ‘Forehead’, ‘Arm’]

6. forEach() method

Using the forEach() method, we will insert the item into the newly generated array if it is not already there.

Program

let arr = ["Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday","Thursday",, "Tuesday", "Monday",];

    function removeDuplicates(arr) {

        let unique = [];

        arr.forEach(element => {

            if (!unique.includes(element)) {

                unique.push(element);

            }

        });

        return unique;

    }

    console.log(removeDuplicates(arr));

Output

(6) [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’]

Conclusion 

You learned about “JavaScript Remove Duplicates From Array” in this article.

In this article, we have explored Six different methods for removing duplicates from an array in JavaScript: using the Set object, using the filter() method, and using the reduce() method and others. Each method has its own advantages and disadvantages, and the best method to use will depend on the specific requirements of your code.

The Set object method is the simplest and most brief method, but it may not work in older browsers that do not support the Set object. The filter() method and the reduce() method are both reliable

FAQ (Frequently Asked Questions)

How can I remove duplicates from an array in JavaScript?

One way to remove duplicate elements from an array in JavaScript is to utilize the Set data structure, which performs this task automatically. Then, by utilizing the Array.from() method, the Set may be transformed into an array once more.

Can I remove duplicates from an array using a loop?

A loop can be used to eliminate duplicate values from an array. Using a nested loop to compare each element of the array with every other element and removing duplicates as you discover them is a typical strategy.

Is it possible to remove duplicates from an array in place (i.e., without creating a new array)?

Duplicates in an array can be eliminated in-place using a loop and the element deletion method splice(). However, this approach can be more difficult and perhaps less successful than creating a new array by using the Set method.

What should I do if I need to preserve the order of the elements in the array?

If you need to retain the order of the elements in the array, you can use a loop and an extra array to keep track of which ones you have already seen. Then, in the order that they occurred in the initial array, you can insert each unique element into a new array.