- 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.
Array.prototype.unique= function ()
return this.reduce(function(previous, current, index, array)
return array.length-1 == index ? Object.keys(previous).reduce(function(prev,cur)
},) : previous;
[ 2, 5, ‘4’, 9, 4, 7 ]
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