I have this Array: [home, info, mail,,,, something, stuff, other]
But I want to remove or replace the ,,
with ,
I tried: allIDs.replace(",,", ",");
But it doesn't seem to work with Arrays
The reason there are empty entries is this:
$(document).find('DIV').each(function(){
allIDs.push(this.id); })
I'm indexing all DIV's ID names, to check if there are duplicates and then rename the currently generated DIV ID..
Alternatively I'd like to find()
only the DIV's that have an ID defined..
I have this Array: [home, info, mail,,,, something, stuff, other]
But I want to remove or replace the ,,
with ,
I tried: allIDs.replace(",,", ",");
But it doesn't seem to work with Arrays
The reason there are empty entries is this:
$(document).find('DIV').each(function(){
allIDs.push(this.id); })
I'm indexing all DIV's ID names, to check if there are duplicates and then rename the currently generated DIV ID..
Alternatively I'd like to find()
only the DIV's that have an ID defined..
6 Answers
Reset to default 2Try $('div[id]')
instead. It will select all div
elements with id
attribute defined.
This works really well:
theArray = theArray.filter(function(e) { return e; });
Change your id
gathering to this...
var allIDs = $(document).find('DIV')
.map(function(){ return this.id || undefined })
.toArray();
If there's no ID on the DIV
, undefined
will be returned, and nothing will be added to the resulting Array.
What you want is to remove the empty values from the Array, not replace the ,,
with ,
i suppose.
Try here
Try to get only div
s with IDs defined:
$(document).find('div[id]').each(function(){
allIDs.push(this.id); });
});
But if you want to clean the array:
allIDs = clean_up(allIDs);
function clean_up(a){
var b = []
for(i in a) if(a[i] && a[i].length) a.push(a[i]);
return a;
}
In javascript, you can't just remove ',,,' in an array to solve the problem.
Do you mean the array ['home', 'info', '', '', '', '', 'mail', 'something', 'stuff', 'other']?
Suppose there is some empty string, and you want to remove them.
You can use a simple javascript function:
allIDs = ["home", "info", "", "", "", "", "mail", "something", "stuff", "other"];
remove_empty_str = function(arr) {
new_array = [];
for (ii = 0, len = arr.length; ii < len; ii++) {
item = arr[ii];
if (item !== "" || item !== null || item !== (void 0)) {
new_array.push(item);
}
}
return new_array;
};
newIDs = remove_empty_str(allIDs);
alert(newIDs);
I would think it's better practice to process the array before do any jQuery output.
You can also re-use remove_empty_str() in other apps too.