Unique Array Filter in Dojo
I was just doing some work that needed some array parsing in JavaScript. I was surprised that I couldn’t find anything that seemed relevant in the Dojo source that would allow me to do this. It’s one of those rare occasions where I assumed Dojo would have it and it didn’t, rather than the usual spend hours coding something to find out I could have just done dojo.doAwesomeStuff() 2 hours earlier.
So I set about trying to find a solution. The problem? I have an array that contains items, I want them to be unique. I want to filter out all the ones that are the same. I want an array_unique like they have in PHP.
I found an interesting chunk of code over here on a blog post that’s about a different problem being solved with Dojo.
Amongst all the other stuff was this snippet:
-
-
cleanFilterValues:function(values) {
-
var unique = {};
-
//get rid of duplicates
-
return dojo.filter(values, function(value) {
-
if (!unique[value]) {
-
unique[value] = true;
-
return true;
-
}
-
return false;
-
}).sort();
-
},
-
I rather liked the look of it. It was super simple. Didn’t need you to loop through the array twice (once to get tha array value and then once over the whole thing again to see if the value you had matched one already in the array). Instead You just sort them all into order and go through them one at a time and don’t return any that are the same as the one before it.
Now of course this won’t work everywhere.
It won’t work where you can’t sort the array for example.
But for what I needed it was perfect. I figured I’d share it.
About this entry
You’re currently reading “Unique Array Filter in Dojo,” an entry on Jon Sykes
- Published:
- 08.16.08 / 1am
- Category:
- Front End Code
QR Code for this Blog Post
4 Comments
Jump to comment form | comments rss [?] | trackback uri [?]