To achieve a unique array in JavaScript, you can use the Object.defineProperty
method along with enumerable
:
Object.defineProperty(Array.prototype, 'getUnique',
{ enumerable: false
, configurable: true
, writable: true
, value: function ()
{ var uniqueObj = {};
var uniqueArr = [];
for (var index = 0, len = this.length; index < len; ++index)
{ if (uniqueObj.hasOwnProperty(this[index])) continue;
uniqueArr.push(this[index]);
uniqueObj[this[index]] = 1;
}
return uniqueArr;
}
});
By default, properties are enumerable in JavaScript, making them visible through different iterations of the array like for-in loops or Object.keys
. However, it's important to note that this method may not work on older browsers that do not support ES5.
Some developers advise against extending native constructors prototypes due to compatibility issues with older browser versions. An alternative approach is to define the function separately:
function getUniqueArray(arr)
{ var u = {};
var a = [];
for (var i = 0, l = arr.length; i < l; ++i)
{ if (u.hasOwnProperty(arr[i])) continue;
a.push(arr[i]);
u[arr[i]] = 1;
}
return a;
}
It's worth mentioning that when using objects as keys in JavaScript, only one object will be printed by the getUnique
function due to their string representation limitation. To overcome this, you may need to iterate through the array each time:
function getUnique(arg)
{
var O = Object(arg);
var len = O.length >>> 0;
var A = [];
var indexOf = function (arg, searchElement)
{ for (var i = 0, l = arg.length; i < l; ++i) if (arg[i] === searchElement) return i;
return -1;
};
for (var k = 0; k < len; ++k)
{ var elementK = O[k];
var kPresent = k in O;
if (!kPresent || indexOf(A, elementK) !== -1) continue;
A[A.length - 1] = elementK;
}
return A;
}