PERFORMANCE ONLY! this code is probably 10X faster than all the codes in here *works on all browsers and also has the lowest memory impact....
and more
if you don't need to reuse the old array;btw do the necessary other operations before you convert it to unique here is probably the fastest way to do this, also very short.
var array=[1,2,3,4,5,6,7,8,9,0,1,2,1];
then you can try this
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 1];
function toUnique(a, b, c) { //array,placeholder,placeholder
b = a.length;
while (c = --b)
while (c--) a[b] !== a[c] || a.splice(c, 1);
return a // not needed ;)
}
console.log(toUnique(array));
//[3, 4, 5, 6, 7, 8, 9, 0, 2, 1]
I came up with this function reading this article...
http://www.shamasis.net/2009/09/fast-algorithm-to-find-unique-items-in-javascript-array/
I don't like the for loop. it has to many parameters.i like the while-- loop.
while is the fastest loop in all browsers except the one we all like so much... chrome.
anyway i wrote the first function that uses while.And yep it's a little faster than the function found in the article.but not enough.unique2()
next step use modern js.Object.keys
i replaced the other for loop with js1.7's Object.keys...
a little faster and shorter (in chrome 2x faster) ;). Not enough!.unique3()
.
at this point i was thinking about what i really need in MY unique function.
i don't need the old array, i want a fast function.
so i used 2 while loops + splice.unique4()
Useless to say that i was impressed.
chrome: the usual 150,000 operations per second jumped to 1,800,000 operations per second.
ie: 80,000 op/s vs 3,500,000 op/s
ios: 18,000 op/s vs 170,000 op/s
safari: 80,000 op/s vs 6,000,000 op/s
Proof
http://jsperf.com/wgu or better use console.time... microtime... whatever
unique5()
is just to show you what happens if you want to keep the old array.
Don't use Array.prototype
if yu don't know what your doing.
i just did alot of copy and past.
Use Object.defineProperty(Array.prototype,...,writable:false,enumerable:false})
if you want to create a native prototype.example: https://stackoverflow.com/a/20463021/2450730
Demo
http://jsfiddle.net/46S7g/
NOTE: your old array is destroyed/becomestheunique after this operation.
if you can't read the code above ask, read a javascript book or here are some explainations about shorter code. https://stackoverflow.com/a/21353032/2450730
some are using indexOf
... don't ... http://jsperf.com/dgfgghfghfghghgfhgfhfghfhgfh
for empty arrays
!array.length||toUnique(array);
o
=object
,a
=array
,i
=index
ande
= umm, something :P – Mottie