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.
Join them; it only takes a minute:
|
||||
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;
|
|||||
|
The easiest way to remove string duplicates is to use associative array and then iterate over the associative array to make the list/array back. Like below:
Voila, now duplicates are gone! |
||||
|
The simplest way to remove a duplicate is to do a for loop and compare the elements that are not the same and push them into the new array
|
||||
|
The following script returns a new array containing only unique values. It works on string and numbers. No requirement for additional libraries only vanilla JS. Browser support:
https://jsfiddle.net/fzmcgcxv/3/
|
|||
|
I know Im a little late, but here is another option using jinqJs
|
|||
|
Vanilla JS solutions with complexity of O(n) (fastest possible for this problem). Modify the hashFunction to distinguish the objects (e.g. 1 and "1") if needed. The first solution avoids hidden loops (common in functions provided by Array).
|
||||
|
|
|||
|
Here is very simple for understanding and working anywhere (even in PhotoshopScript) code. Check it!
|
|||
|
|
|||
|
_.uniq(peoplenames)
solves this lodash.com/docs#uniq – Connor Leech Jul 29 '14 at 19:29