Делаем просто:
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];
const keys = new Set;
this.length -= this.reduce((acc, n, i, a) => {
a[i - acc] = n;
const k = getKey(n);
return acc + (keys.has(k) || !keys.add(k));
}, 0);
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']