How to Remove Duplicates Elements from an Array in Javascript?

Sep 21, 2022 . Admin



Hello dev,

This article is focused on how to remove duplicates element from an array in javascript. if you want to see example of how to remove duplicates item from an array in javascript then you are a right place. it's simple example of how to remove duplicates values in an array using javascript.

In this example, I am going to explain to you to remove duplicate elements from an array in javascript. Remove duplicates from an array using a Set, First, convert an array of duplicates to a Set. The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.

In the second example we have another method to remove duplicate elements from an array. The include() returns true if an element is in an array or false if it is not. The following example iterates over elements of an array and adds to a new array only elements that are not already there

So, let's see bellow solution:

Example: 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove Duplicates Elements from an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove Duplicates Elements from an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            let chars = ['A', 'B', 'A', 'C', 'B'];
            let uniChars = [...new Set(chars)];

            //Give output to console...
            console.log(uniChars);
        </script>
    </body>
</html>
Output:
['A', 'B', 'C']
Example: 1 index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Remove Duplicates Elements from an Array in Javascript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Remove Duplicates Elements from an Array in Javascript? -  MyWebtuts.com</h1>
        
        <script type="text/javascript">
            let chars = ['A', 'B', 'A', 'C', 'B'];
            let uniChars = [];
            chars.forEach((c) => {
                if (!uniChars.includes(c)) {
                    uniChars.push(c);
                }
            });

            //Give output to console...
            console.log(uniChars);
        </script>
    </body>
</html>
Output:
['A', 'B', 'C']
I hope it will help you...
#Javascript