How to Remove Duplicate Elements from Array in JavaScript
Arrays in JavaScript are daunting and particularly difficult in nature. The fundamental reason for making this statement is that JavaScript does not provide as many functions/methods for array operations as several other languages do. As a result, an array operation as simple as removing duplicate elements from an array may also be particularly intimidating.
A possible approach for accomplishing this task of removing duplicate elements from an array in JavaScript is using the method reduce(). The method reduce() performs execution of the callback function for every element present in the array. It automatically excludes all the holes in the array and expects 4 arguments. These arguments include –
- Initial value
- Value of the current element
- Current index
- Array to be used for iterations
On its first execution, if the initial value is provided, the value of the previous value is equal to the initial value and the current value is equal to the value of the first element of the array. On the other hand, if no initial value is given, the value of previous is equal to the value of the first element of the array and the value of current is equal to the value of the second element of the array.
In order to understand the concept, let us consider an example.
[js]
Array.prototype.unique= function ()
{
return this.reduce(function(previous, current, index, array)
{
previous[current.toString()+typeof(current)]=current;
return array.length-1 == index ? Object.keys(previous).reduce(function(prev,cur)
{
prev.push(previous[cur]);
return prev;
},[]) : previous;
}, {});
};
console.log([2,5,"4", 9,4,2,7,2].unique());
[/js]
Output:
[js]
[ 2, 5, ‘4’, 9, 4, 7 ]
[/js]
The methodology followed in the example illustrated above, adds a method named unique() in the prototype of Array class. This method unique() makes use of the method reduce(). The argument given for initial value is an empty map. In the call-back method, we are pushing unique key value pairs of the map thereby eliminating the duplicate elements. The method Object.keys() provides these unique keys. The nested method reduce() returns the key values in the form of an array.
Besides this, code is also equipped to handle the case where a user enters a string and an integer of the same value. An example of this scenario is “4″ and 4. In order to handle such a situation, the example makes use of the typeof() method, which is concatenated with current.toString(). This ensures that different type of values, numerals and alphabets are identified separately and handled as found appropriate.
Try it on online node console www.node-console.com