Search code examples
javascriptarraysis-empty

Check if a sparse array is empty


I have a sparse array; that is, an array in which some elements have been deleted. Elements are constantly being added and deleted from the middle, so it is very large and very sparse.

At some point, every element will be undefined, but the length won't be 0 — so it is empty, but it doesn't express that. How can I check if this has happened?

The best that I can think of is to loop through the whole monster and check if they're all undefined. But that would be too inefficient for my application.


Solution

  • Two solutions I can think of. Both require some modification to your interactions with the array.

    First solution

    Keep a counter.

    If you simply keep a counter that represents how many elements in the array are actually there, then the emptiness check is a mere comparison.

    var n = 0;
    
    // Adding something to the array:
    myArr[2] = somethingDefined;
    n ++;
    
    // Removing from the array:
    delete myArr[2];
    n --;
    
    // Check if empty
    if(n == 0) {
       console.log("myArr is empty.");
    }
    

    Second solution

    Use splice instead of delete

    splice will actually modify the array instead of setting the values to undefined. Example:

    myArr.splice(2, 1); // Get rid of myArr[2]
    

    And this mutates the array and will change .length so you can easily check the actual length of the array. Note that splice is less efficient (and given you seem to care about the efficiency, the first solution is probably more applicable).