This seems like such a simple need but I've spent an inordinate amount of time trying to do this to no avail. I've looked at other questions on SO and I haven't found what I need. I have a very simple JavaScript array such as peoplenames = new Array("Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl");
that may or may not contain duplicates and I need to simply remove the duplicates and put the unique values in a new array. That's it. I could point to all the codes that I've tried but I think it's useless because they don't work. If anyone has done this and can help me out I'd really appreciate it. JavaScript or jQuery solutions are both acceptable.
|
||||
add comment |
Quick and dirty using jQuery:
|
|||||||||||||
|
Got tired of seeing all bad examples with for-loops or jQuery. Javascript has the perfect tools for this nowadays: sort, map and reduce. Uniq reduce while keeping existing order
Faster uniq with sortingThere are probably faster ways but this one is pretty decent.
|
||||
|
Use Underscore.jsIt's a library with a host of functions for manipulating arrays.
Note: Lo-Dash (an underscore competitor) also offers a comparable .uniq implementation. |
||||
|
Less code than you might think.
or, using the 3rd ("this array") parameter of the
A word of warning: A more realistic version that tries to use hash lookups when possible:
This will be linear for arrays of primitives, but still quadratic for objects. While above code is based on strict comparison (
This is particularly useful when comparing objects that are different but "look" the same:
|
|||||||||||||||||||||
|
A slight modification of thg435's excellent answer to use a custom comparator:
|
|||
|
If you're creating the array yourself, you can save yourself a loop and the extra unique filter by doing the check as you're inserting the data;
|
|||
|
If you don't want to include a whole library, you can use this one off to add a method that any array can use:
|
|||
|
A single line version using array filter and indexOf functions:
|
|||
|
The top answers have complexity of
This will work for strings, numbers, and dates. If your array contains complex objects (ie, they have to be compared with
|
|||||||||||||||||||||
|
|
|||
|
Here is another approach using jQuery,
Author: William Skidmore |
|||
|
The following is more than 80% faster than the jQuery method listed (see tests below). It is an answer from a similar question a few years ago, if I come across the person who originally proposed it I will post credit. Pure JS.
My Test Case comparison: http://jsperf.com/remove-duplicate-array-tests |
|||||||||||||||||
|
You can always try putting it into an object, and then iterating through its keys:
|
||||
|
You could also use the However, the code there isn’t very well written, since it declares the |
|||
|
peoplenames = ["Mike",...];
– mgraph Feb 10 '12 at 15:01