Remove Duplicate Elements from an Array in JavaScript



To remove duplicate elements from an array in Javascript can be achieved using various approaches. We will be understanding six different approaches in this article, which can be used according to our requirement in various cases.

In this article we are having a Javascript array and our task is to remove duplicate elements from array in JavaScript.

Duplicate array example

Approaches to Remove Duplicate Elements From an Array

Here is a list of approaches to remove duplicate elements from an array in JavaScript which we will be discussing in this article with stepwise explanation and complete example codes.

Using Set() Method

To remove duplicate elements from array in JavaScript, we have used set() method. A set is a collection of unique values and holds only unique values.

  • We have used two div elements to display the given array and result. We have also used a button which triggers unique() function upon clicking on the button.
  • We have used getElementById() method to get the div and innerHTML to display the array and the result.
  • We have used new Set(arr) to convert array arr into set. Since set contains only unique values, it removes any duplicate values.
  • Then we have used spread operator(...) to convert set to array containing unique values and stored it in newArray.

Example

Here is a complete example code implementing above mentioned steps to remove duplicate elements from an array in JavaScript using set() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <h2>
        Removing Duplicate Elements From an Array in JavaScript
    </h2>
    <p>
        In this example we have used <strong>set()</strong>
        method to remove duplicate elements from an array in 
        JavaScript.
    </p>
    <hr>
    <div id="array"></div>
    <br>
    <button onclick="unique()">Unique array</button>
    <br><br>
    <div id="result"></div>
    <script>
        var arr = ["steve", "mark", "mark", "bill", "steve", "Zoro"];
        document.getElementById("array")
            .innerHTML = "Initial array: " + arr;
        function unique() {
            let newArray = [...new Set(arr)];
            document.getElementById("result")
                .innerHTML = "Unique array: " + newArray;
        }
    </script>
</body>
</html>

Using filter() Method

In this approach to remove duplicate elements from array in JavaScript, we have used filter() method with indexOf() method.

  • We have used arr.filter() method that creates a new array newArray from original array arr.
  • The filter method includes elements in newArray which pass the condition arr.indexOf(item) === index.
  • Here, item represents current element being processed and index represents index of the current element.
  • The indexOf(item) method returns the index of first occurence of item in the array. If it matches the condition arr.indexOf(item) === index that is, if index of first occurence of any element is same as the index, which means that index is the first occurence in array and gets included in newArr.
  • If any element fails to match the condition arr.indexOf(item) === index then that element is duplicate element and not included in newArray.

Example

Here is a complete example code implementing above mentioned steps to remove duplicate elements from an array in JavaScript using filter() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <h2>
        Removing Duplicate Elements From an Array in JavaScript
    </h2>
    <p>
        In this example we have used <strong>filter()</strong>
        method to remove duplicate elements from an array in 
        JavaScript.
    </p>
    <hr>
    <div id="array"></div>
    <br>
    <button onclick="unique()">Unique array</button>
    <br><br>
    <div id="result"></div>
    <script>
        var arr = ["steve", "mark", "mark", "bill", "steve", "Zoro"];
        document.getElementById("array")
            .innerHTML = "Initial array: " + arr;
        function unique() {
            let newArray = arr.filter((item, index) => 
                arr.indexOf(item) === index);
            document.getElementById("result")
                .innerHTML = "Unique array: " + newArray;
        }
    </script>
</body>
</html>

Using reduce() with includes() Method

In this approach we have used reduce() method with includes() method to remove duplicate elements from array in JavaScript. The reduce() method executes a reducer function on each element of the array.

  • We have used a reducer function with paramerters as acc and curr. The acc represents initial or previously returned value and curr represents current element being processed.
  • Then We have used if/else conditional statement with includes() method which checks if curr element already exists in the acc array.
  • If curr element is not present in acc array then curr element is pushed in the acc array using push() method. This lets only unique element to be added in array.
  • At the end, the updated acc is returned for next iteration.

Example

Here is a complete example code implementing above mentioned steps to remove duplicate elements from an array in JavaScript using reduce() with includes() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <h2>
        Removing Duplicate Elements From an Array in JavaScript
    </h2>
    <p>
        In this example we have used <strong>reduce()</strong>
        with <strong>includes()</strong> method to remove 
        duplicate elements from an array in JavaScript.
    </p>
    <hr>
    <div id="array"></div>
    <br>
    <button onclick="unique()">Unique array</button>
    <br><br>
    <div id="result"></div>
    <script>
        var arr = ["steve", "mark", "mark", "bill", "steve", "Zoro"];
        document.getElementById("array")
            .innerHTML = "Initial array: " + arr;
        function unique() {
            var newArray = arr.reduce(function (acc, curr) {
                if (!acc.includes(curr))
                    acc.push(curr);
                return acc;
            }, []);
            document.getElementById("result")
                .innerHTML = "Unique array: " + newArray;
        }
    </script>
</body>
</html>

Using forEach() with includes() Method

In this approach we have used forEach() method with includes() method to remove duplicate elements from array in JavaScript.

  • We have initialized a new empty array newArray. Then we have used forEach() method to iterate over elements in original array arr.
  • The newArray.includes(c) returns true if c(current element) is already present in newArray.
  • Then we have used if/else conditional statement to push c(current element) into array if it is not present in newArray. So, only unique value is pushed in newArray.

Example

Here is a complete example code implementing above mentioned steps to remove duplicate elements from an array in JavaScript using forEach() with includes() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <h2>
        Removing Duplicate Elements From an Array in JavaScript
    </h2>
    <p>
        In this example we have used <strong>forEach()</strong>
        with <strong>includes()</strong> method to remove
        duplicate elements from an array in JavaScript.
    </p>
    <hr>
    <div id="array"></div>
    <br>
    <button onclick="unique()">Unique array</button>
    <br><br>
    <div id="result"></div>
    <script>
        var arr = ["steve", "mark", "mark", "bill", "steve", "Zoro"];
        document.getElementById("array")
            .innerHTML = "Initial array: " + arr;
        function unique() {
            let newArray = [];
            arr.forEach((c) => {
                if (!newArray.includes(c)) {
                    newArray.push(c);
                }
            });
            document.getElementById("result")
                .innerHTML = "Unique array: " + newArray;
        }
    </script>
</body>
</html>

Using Underscore.js _.uniq() Method

In this approach to remove duplicate elements from array in JavaScript we have used _.uniq() method of Underscore.js library.

  • We have used script tag in head section to include the Underscore.js library allowing us to use its function like ._uniq() method.
  • We have used _.uniq() method which returns an array of unique values from an array (here arr).
  • Here, the array of unique value is stored in newArray.

Example

Here is a complete example code implementing above mentioned steps to remove duplicate elements from an array in JavaScript using Underscore.js _.uniq() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Removing element from Array in Javascript
    </title>
    <script src="https://unpkg.com/[email protected]/underscore-min.js"></script>
</head>
<body>
    <h2>
        Removing element from Array in Javascript
    </h2>
    <p>
        In this example, we have used <strong>Underscore.js _.uniq()
        </strong> method for removing an element from an Array
        Javascript.
    </p>
    <hr>
    <div id="array"></div>
    <br>
    <button onclick="unique()">Unique array</button>
    <br><br>
    <div id="result"></div>
    <script>
        var arr = ["steve", "mark", "mark", "bill", "steve", "Zoro"];
        document.getElementById("array")
            .innerHTML = "Initial array: " + arr;
        function unique() {
            let newArray = _.uniq(arr);
            document.getElementById("result")
                .innerHTML = "Initial array: " + newArray;
        }
    </script>
</body>
</html>

Using Lodash _.uniq() Method

In this approach we have used Lodash library to remove duplicate elements from an array in JavaScript. We have used _.uniq() method of Lodash library to removes the duplicate elements from the array.

  • We have used script tag in head section to include the Lodash library from a Content Delivery Network (CDN) to add Lodash's utility functions which allows us to use lodash methods such as _.uniq().
  • We have used Lodash _.uniq() method, which removes all the duplicate elements from the array.

Example

Here is a complete example code implementing above mentioned steps to remove duplicate elements from an array in JavaScript using Lodash _.uniq() method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Removing element from Array in Javascript
    </title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
</head>
<body>
    <h2>
        Removing element from Array in Javascript
    </h2>
    <p>
        In this example, we have used <strong>Lodash _.uniq()
        </strong> method for removing an element from an Array
        Javascript.
    </p>
    <hr>
    <div id="array"></div>
    <br>
    <button onclick="unique()">Unique array</button>
    <br><br>
    <div id="result"></div>
    <script>
        var arr = ["steve", "mark", "mark", "bill", "steve", "Zoro"];
        document.getElementById("array")
            .innerHTML = "Initial array: " + arr;
        function unique() {
            let newArray = _.uniq(arr);
            document.getElementById("result")
                .innerHTML = "Initial array: " + newArray;
        }
    </script>
</body>
</html>

Conclusion

In this article, we have understood how to remove duplicate elements from an array in JavaScript. We have learnt six different approaches, some of them are by using set()method, filter() method, by reduce() with includes() method, forEach() with includes() method and so on. Out of all the approaches, using set() method is mostly used as it does not accept any duplicate value.

Updated on: 2024-11-18T16:29:05+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements