An array is a very useful data type to store multiple values in a structural way in every programming language. While in web development, JavaScript handles front-end data storage. Manipulating arrays is pretty common in JavaScript. It contains operations like adding, removing or deleting some elements from an array.
But sometimes, we need to remove duplicate elements from the array so we can process array data as unique. There are many ways to perform this operation manually or using in-built functions.
In this article, we will below two methods to remove duplicate values or elements from an array.
- Using Array indexOf() method
- Using includes() method
Here both methods serve same purpose but with different functionality or logic. It's up to you to choose.
Remove Duplicate Using indexOf() method
In this method, we will loop through array and get indexOf each element. Then it will check the element exists in an array or not. If an element is already in array then it will remove that element from array.
At end of the loop, it will contain only unique elements. While in a loop it search element every time and make decision-based on result.
Let's take an example to understand how it works:
It will produce output like below:
In the above code, we have created a function which will take array as a parameter and then it will cycle all element into loop. In a loop, it will check element exists or not. If an element do not exist in an array then it will add it. At last, function will return a new array containing unique values and prints it.
Remove Duplicate Elements Using includes() Function
The includes() function works same as in array in other programming languages like PHP. It will check array contains particular value or not.
In this method, we will use includes() function same as previous. We'll loop through all elements and then use this function to find out value exists in array or not and perform action based on function return. Let's create another example same as previous:
It will print output like below :
Both methods loop through all values and then create a new array with unique value. Both functions has it's unique functionality and it depends on how you use it. Here, both example returns same output using different methods.
Conclusion
In this article, we have created a new array with unique values or other words removed duplicate elements from array using indexOf() and includes() functions. Those functions are regularly used in web developments.