Unique filter on Arrays

Excerpt

Implement an efficient unique filter on arrays

The Array object has a lot of native functions to use and manipulate arrays. However a unique() function is missing. I wrote my own (badly) implementation.
Later I discovered that it can be done by a single statement.
Later I discovered that it was already implemented as a proposal for the future.

Extending the Array object

The Array object can be extended by a simple unique function like:

Array.prototype.unique = function () { return [...new Set(this)] };

This will allow using the unique functions on array with primitive values:


const arr = [1, 1, 2, 3, 3, 4, 4, 4, 5, 5];
console.info('unique:', arr.unique());
    

In JavaScript it is a common implementation pattern that a function can be passed by a parameter to customize the behavior like the sort() function does. On a unique function this is required as well to enable using it for more complex data objects.

In github in the repo https://github.com/tc39 you can find the proposals for upcoming JavaScript features like the proposal-array-unique repo.

Here they propose the name uniqueBy(f) and also have a polyfill implementation that the :


if (typeof Array.prototype.uniqueBy !== 'function') {
  Object.defineProperty(Array.prototype, 'uniqueBy', {
    writable: true,
    configurable: true,
    value: function (f = undefined) {
      if (!f) return [...new Set(this)];
      const map = new Map();

      for (const item of this) {
        const key = f(item);
        if (!map.has(key)) { map.set(key, item); }
      }

      return [...map.values()];
    }
  });
}
    

Example

You can find a implementation on using both functions in the script of this page. Happy debugging.

Summary

Now you are aware of features that will probably be implemented on the next time so you can stick to this design and get some polyfill code as well. There is a chance that this will be implemented as native function in the future.

See Also

Tags

JavaScript