Loading...

Remove duplicate from an array in JavaScript

Remove duplicate from an array in JavaScript

Arrays help store data in a sequence. There might be chances where we mistakenly store duplicate values in an array. Here comes the need to remove the duplicate values from that array. One of the most asked questions in many interviews is regarding removing duplicates from an array.

Various methods of removing duplicates from an array

There are many ways in which we can remove them. Let us discuss some of them in detail.

1) Using the filter() method

This method creates a new array that passes the conditions that we provide and any element that doesn’t pass the conditions that we provide, is removed from the new array created. We can also get the duplicate values from an array by a simple change in our code. Let us see an example of this method.

Example 01: Removing duplicates from an array

<script> 

     var arr = ["january", "february", "january",  "march", "february", "february"];   

     function removeDuplicates(arr) { 

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

     }    

     console.log(removeDuplicates(arr)); 

</script>   

You will get the output as shown below

[“january”, “february”, “march”]

Example 02: Retrieving duplicates from an array

<script> 

     var arr = ["january", "february", "january",  "march", "february", "february"];   

     function getDuplicates(arr) { 

            return arr.filter((item, index) => arr.indexOf(item) !== index);

     }    

     console.log(removeDuplicates(arr)); 

</script>   

You will get the output as shown below

[“january”, “february”]

2) Using the set() method

A set in JavaScript is a collection of unique values. In this method, the first step is the conversion of an array containing duplicates to a set. The new set that has formed contains elements from the array removing duplicates implicitly. After it, the set is converted back to an array. With the following steps, we will be successful in removing the duplicates from an array. Let us see an example.

<script> 

    var arr = ["january", "february", "january", "march", "february", "february"];

    function removeDuplicates(arr) { 

        return [...new Set(arr)]; 

   } 

    console.log(removeDuplicates(arr)); 

</script>

You will get the output as shown below

[“january”, “february”, “march”]

3) Using the for each method

This method calls a function for each element in an array. It is not executed for empty elements. In this method, we move over elements that are present in the array and push those elements that don’t exist in the array to a new array. Let us understand the working of this method with the help of an example.

<script> 

    var arr =  ["january", "february", "january", "march", "february", "february"];

    function removeDuplicates(arr) { 

        var unique = [ ] ;

        arr.forEach(element => { 

            if (!unique.includes(element)) { 

               unique.push(element); 

            } 

        });

        return unique;

    } 

    console.log(removeDuplicates(arr)); 
</script>

You will get the output as shown below

[“january”, “february”, “march”]

4) Using the reduce() method

This method executes a reducer function for an element of the array. It returns a single value. It is not executed for an array with empty elements. With this method, there will not be any change in the original array. It reduces the elements of the array and combines them into a final array which is based on a reducer function. Let us understand the working of this method with the help of an example.

<script> 

    var arr = ["january", "february", "january", "march", "february", "february"];     

    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)); 

</script>

You will get the output as shown below

[“january”, “february”, “march”]

We can also use this reduce method with a different approach

<script> 

    var arr = ["january", "february", "january", "march", "february", "february"];

    function removeDuplicates(arr) {

           let unique = arr.reduce(function (a, b) {

                if (a. indexOf(b) < 0) a>push(b);

           }, []);

           return unique;

   }

   console.log(removeDuplicates(arr))

</script>

You will get the output as shown below

[“january”, “february”, “march”]

5) By property name

We can remove duplicate objects from an array of objects with their property name. Let us understand the working of this method with the help of an example.

var users = [

      { name: “Ajay”, height: 170, weight: 60 },

      { name: “Aman”, height: 176, weight: 63 },

      { name: “Alok”, height: 185, weight: 90 },

      { name: “Ajay”, height: 170, weight: 60 },

      { name: “Aman”, height: 176, weight: 63 }

]

function uniqByKeepLast( data, key) {

      return [

          …new Map(

                data.map( x => [key(x), x])

          ).values( )

      ]

}

console.log(JSON.stringify(uniqByKeepLasg(users, it => it.name)));

You will get the output as shown below

 { name: “Ajay”, height: 170, weight: 60 },

 { name: “Aman”, height: 176, weight: 63 },

 { name: “Alok”, height: 185, weight: 90 },

6) By using underscore JS

We can directly produce an array of elements without duplicating by using the .uniq method. Let us understand the working of this method with the help of an example.

<script>

    var arr = ["january", "february", "january", "march", "february", "february"];

    console.log(_.uniq( arr, false)) ;

</script>

You will get the output as shown below

[“january”, “february”, “march”]

Conclusion

This was all about Removing duplicates from an array in JavaSript. If you are interested in learning JavaScript, do check out courses on codedamn with an in-built environment playground to learn and practice code. Join the community of codedamn and do check out other articles related to programming and development on codedamn and subscribe to our newsletter to never miss out on our new programs and updates.

 

Sharing is caring

Did you like what Agam singh, Aman Ahmed Siddiqui, Aman Chopra, Aman, Amol Shelke, Anas Khan, Anirudh Panda, Ankur Balwada, Anshul Soni, Arif Shaikh, wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far