4

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..

costa
  • 1,077
  • 1
  • 9
  • 21
TrySpace
  • 2,233
  • 8
  • 35
  • 62

6 Answers6

2

Try $('div[id]') instead. It will select all div elements with id attribute defined.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
2

This works really well:

theArray = theArray.filter(function(e) { return e; });
uınbɐɥs
  • 7,236
  • 5
  • 26
  • 42
Flex Elektro Deimling
  • 1,599
  • 1
  • 17
  • 16
1

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.

0

What you want is to remove the empty values from the Array, not replace the ,, with , i suppose.

Try here

Community
  • 1
  • 1
costa
  • 1,077
  • 1
  • 9
  • 21
0

Try to get only divs 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;
}
iambriansreed
  • 21,935
  • 6
  • 63
  • 79
0

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.

Edditoria
  • 199
  • 1
  • 15