Removing duplicates from an array using JavaScript #coding #programming

Posted by

Removing Duplicates from an Array using JavaScript

Removing Duplicates from an Array using JavaScript

In this article, we will discuss how to remove duplicates from an array using JavaScript.

Code Implementation

Here is a simple JavaScript function that removes duplicates from an array:

        
            function removeDuplicates(arr) {
                return [...new Set(arr)];
            }

            // Sample array with duplicates
            const array = [1, 2, 3, 4, 1, 2, 5];

            // Call the function to remove duplicates
            const result = removeDuplicates(array);

            // Print the result
            console.log(result); // [1, 2, 3, 4, 5]
        
    

As shown in the code snippet above, we define a function removeDuplicates that takes an array as input and uses the Set object to remove duplicates. Finally, we convert the Set object back to an array using the spread operator [... ].

Conclusion

Removing duplicates from an array is a common task in programming. By using the Set object in JavaScript, we can easily remove duplicates from an array and obtain a new array with unique elements.

Thank you for reading this article. Happy coding!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@codeblockdev
5 months ago