Removing duplicates from comma-separated list
I am generating a comma-separated list out of the rel-attributes of several li-elements, using the map-function.
poiSelectedList = $('#poiList li li.selected').map(function() { return $(this).attr('rel'); }).get().joi开发者_开发问答n(',');
How can I assure that there are no duplicates inside my list?
You could make a cache like this:
var cache = [];
poiSelectedList = $('#poiList li li.selected').map(function() {
var rel = $(this).attr('rel');
if(cache.indexOf(rel) === -1) {
cache.push(rel);
return rel;
} else {
return undefined;
}
}).filter(function(a, b) {
return b !== undefined;
}).get().join(',');
Or, as patrick dw suggested, a more concise version:
var cache = [];
$('#poiList li li.selected').each(function() {
var rel = $(this).attr('rel');
if(!$.inArray(rel, cache)) {
cache.push(rel);
}
});
var poiSelectedList = cache.join(); // defaults to ,
You could do:
var duplicates = {};
poiSelectedList = $('#poiList li li.selected').map(function() {
var rel = $(this).attr('rel');
if (duplicates[rel] !== true){
duplicates[rel] = true;
return rel;
}
}).get().join(',');
While this is not short nor good-looking, it should be a fast way
var poiSelectedList='';
var tmp;
$('#poiList li li.selected').each(function() { tmp[$(this).attr('rel')]=1; });
var comma=0;
for(var i in tmp) if (tmp.hasOwnProperty(i)){
if(comma){poiSelectedList+=','}else{comma=1}
poiSelectedList+=i;
}
Use jQuery
var poiSelectedList = $('#poiList li li.selected').map(function() {
return $(this).attr('rel');});
$.unique(poiSelectedList);
poiSelectedList.get().join(',');
精彩评论