Делаем просто:
Array.prototype.unique = function() {
this.splice(0, this.length, ...new Set(this));
return this;
};
Делаем сложно:
Array.prototype.unique = function(key = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
let numDeleted = 0;
this.forEach(function(n, i, a) {
a[i - numDeleted] = n;
const k = getKey(n);
numDeleted += this.has(k) || !this.add(k);
}, new Set);
this.length -= numDeleted;
return this;
};
[ 1, 1, 1, 2 ].unique() // [1, 2]
[ { id: 3 }, { id: 1 }, { id: 1 }, { id: 3 } ].unique('id') // [{id: 3}, {id: 1}]
[ 'a', 'b', 'c', 'd', 'ab', 'bc' ].unique(n => n.length) // ['a', 'ab']