Why is there no Array.unique ?

Over time, because of repeated usage, I have defined

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

Because it is so frequently needed (and these are the first set of examples I copy and paste from a code base):

  [ ...events_times, ...events_entry ].uniq ()
    .sort ((a, b) => util_sort_cmp_num (a.timestamp, b.timestamp) || util_sort_cmp_str (a.event, b.event))

  const keys = [ ...keys_locate ('MAPI_'), ...keys_locate ('ACNT_') ].uniq ();

  'symbols': trades.map (({ symbol }) => symbol).uniq ().sort ()

  const possible = [ ...selection, ...activated, ...interested ].uniq ().sort ();

  return components.map (({ metadata }) => metadata?.labels?.app).notnull ().uniq ().sort ();

  const changes = updates.map (id => content [id].index).uniq ().sort (util_sort_cmp_num)

  const times = Object.keys (times1).intersection (Object.keys (times2)).uniq ();

I understand a point about using Sets in these cases, but the vast majority of code works on Arrays and its clunky to use a Set for a singular intermediate need. In the same way I have defined my own intersection, excluding and symmetricDifference operators for Arrays because again, the data is in an Array and then needs to go into something else that works from Array. Which raises a more general point about Set operations that should work with Array's so that code bases can remain cleaner to operate on one style of container.

See GitHub - tc39/proposal-array-unique: ECMAScript proposal for Deduplicating method of Array

Also, please do not modify objects you don't own, especially globals/builtins.

Thanks, the language allows me to modify the builtins, so I have done so when the builtins are clearly deficient, especially when it's my code base and I can do as I please. I will read the proposal. But I also made a larger point: there are other Set style operations that would be beneficial to be supported by Array.

Doing so damages the entire web, and others doing so has held back the evolution of the language many times. In particular, there will likely never again be new Array prototype methods because so many people "did as they pleased".

You may find https://humanwhocodes.com/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/ and https://kettanaito.com/blog/why-patching-globals-is-harmful helpful reads.

3 Likes