Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to remove duplicate elements from JavaScript Array ?

  • Last Updated : 20 Oct, 2021

There are various methods to remove duplicates in the array. We will discuss the most common four ways.

Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Javascript




<script>
    var arr = ["apple", "mango", "apple"
            "orange", "mango", "mango"];
  
    function removeDuplicates(arr) {
        return arr.filter((item, 
            index) => arr.indexOf(item) === index);
    }
  
    console.log(removeDuplicates(arr));
</script>


Output:



["apple", "mango", "orange"]

Using a Set() Method: This method sets a new object type with ES6 (ES2015) that allows you to create collections of unique values.

Javascript




<script>
    var arr = ["apple", "mango", "apple",
            "orange", "mango", "mango"];
  
    function removeDuplicates(arr) {
        return [...new Set(arr)];
    }
  
    console.log(removeDuplicates(arr));
</script>


Output:

["apple", "mango", "orange"]

Using the forEach() Method: By using forEach() method, we can iterate over the elements in the array, and we will push into the new array if it doesn’t exist in the array.

Javascript




<script>
    var arr = ["apple", "mango"
        "apple", "orange", "mango", "mango"];
  
    function removeDuplicates(arr) {
        var unique = [];
        arr.forEach(element => {
            if (!unique.includes(element)) {
                unique.push(element);
            }
        });
        return unique;
    }
  
    console.log(removeDuplicates(arr));
</script>


Output:

["apple", "mango", "orange"]

Using the reduce() Method: The reduce() method is used to reduce the elements of the array and combine them into a final array based on some reducer function that you pass.

Javascript




<script>
    var arr = ["apple", "mango"
        "apple", "orange", "mango", "mango"];
  
    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>


Output:

["apple", "mango", "orange"]



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!