function array_unique(nav_array) {
nav_array = nav_array.sort(function (a, b) { return a*1 - b*1; });
var ret = [nav_array[0]];
// Start loop at 1 as element 0 can never be a duplicate
for (var i = 1; i < nav_array.length; i++) {
if (nav_array[i-1] !== nav_array[i]) {
ret.push(nav_array[i]);
}
}
return ret;
}
function array_unique(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) == -1) {
result.push(arr[i]);
}
}
return result;
}
Not a built in function. If the product list does not contain the item, add it to unique list and return unique list.
Since there's no built-in reverse indexof, I reverse the array, filter out duplicates, then re-reverse it.
The filter function looks for any occurence of the element after the current index (before in the original array). If one is found, it throws out this element.
Edit:
Alternatively, you could use lastindexOf (if you don't care about order):
Array.prototype.unique = function()
{
var tmp = {}, out = [];
for(var i = 0, n = this.length; i < n; ++i)
{
if(!tmp[this[i]]) { tmp[this[i]] = true; out.push(this[i]); }
}
return out;
}
var a = [1,2,2,7,4,1,'a',0,6,9,'a'];
var b = a.unique();
alert(a);
alert(b);
I like to use this. There is nothing wrong with using the for loop, I just like using the build-in functions. You could even pass in a boolean argument for typecast or non typecast matching, which in that case you would use a for loop (the filter() method/function does typecast matching (===))
Array.prototype.unique =
function()
{
return this.filter(
function(val, i, arr)
{
return (i <= arr.indexOf(val));
}
);
}
Those of you who work with google closure library, have at their disposal goog.array.removeDuplicates, which is the same as unique. It changes the array itself, though.
Here is the way you can do remove duplicate values from the Array.
function ArrNoDupe(dupArray) {
var temp = {};
for (var i = 0; i < dupArray.length; i++) {
temp[dupArray[i]] = true;
var uniqueArray = [];
for (var k in temp)
uniqueArray.push(k);
return uniqueArray;
}
}