1

My implementation is such that i have :

var test = [{},{},{}];

My test var is an array of objects. In this the last object can be empty or have keys.

I need to remove this last object always if it is empty.

What i have written right now works and its thus :

var lengthofTest = test.length;
if(Object.keys(test[lengthofTest]).length == 0) {
 test.pop();
 }

Is there a better way of doing it? Anything more direct?

Bhumi Singhal
  • 8,063
  • 10
  • 50
  • 76

1 Answers1

3

Is there a better way of doing it?

Depends on your definition of "better." :-) For me, that's a good way except for a couple of details:

  1. You'll want test[lengthofTest - 1], not test[lengthofTest]. (Remember, indexes start at 0, so it's 0 through length - 1.)

  2. You don't need the variable

  3. There's no need for pop if you're not using the result, just decrement length

So:

if (Object.keys(test[test.length - 1]).length == 0) {
  --test.length;
}

Anything more direct?

You could use for-in:

var lengthofTest = test.length;
for (var key in test[lengthofTest-1]) {
    if (test[lengthofTest-1].hasOwnProperty(key)) {
        --test.length;
        break;
    }
}

...but as you can see it's a lot more verbose, and in the above it's assuming no non-index properties on the array (details about what I mean by that in this other answer).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875