For a long time I have wanted an Array.prototype.unique() method.
This method would return a unique set of elements contained in an Array.
I would easily see this signature: Array.prototype.unique(sorted, callback)
Array.prototype.unique(callback)
, where:
sorted
is a boolean (optional, default=false), indicating whether the Array is already sorted or not for optimizations. If it is wrongly true, an exception should be thrown-
callback
is a function (optional too) that is given two elements of the array (like the callback of Array.prototype.sort) and is expected to return true if they are considered as equal.
If the callback is not provided, the function would run as if the provided callback would return the result of a strict equality (i.e. callback = function(a, b) { return a === b; };
Even though having a unique Array is already possible in EcmaScript 6 using [...new Set(...myArray)]
, or using Array.prototype.filter()
with the appropriate callback, I think this function would be more convenient, more concise and easier to read.
What do you think?
Edit: In retrospection, maybe the assertion that the Array is sorted could be made by default and be rejected if an element is expected to be put before its predecessor. Therefore, the sorted
parameter is not necessary. Moreover, checking that the Array is sorted would have been hard to spec with the callback.
Florent