Lobe
Lobe

Reputation: 538

Find Javascript array length without deleted items

Just a simple question that I can't seem to find the answer to.

myarray.length()

The above will return the length including deleted items. How do I get the length without deleted items? Thanks

EDIT:

Thanks for the answers. I am deleting by writing 'delete myarray[0]' and this works well. Other sections of the script rely on the length() method to return the length including deletes. The splice method looks like what I want, so I'll try this

Upvotes: 6

Views: 5715

Answers (4)

Paweł
Paweł

Reputation: 4516

You can use for..in loop, which ommits deleted items.

var a = [1,2,3,4,5];
delete a[0];
delete a[1];

for(var i=0;i<a.length;i++){}
console.log(i); //5

var j=0;
for(var i in a){j++;}
console.log(j); //3

Upvotes: 2

tobek
tobek

Reputation: 4539

If for some reason you do want to use sparse arrays (totally legitimate) but want to count the number of defined elements, you can just use reduce(), for example:

var arr = [1, 2, undefined, 3, undefined, undefined, 4];
arr.reduce(function(prev, curr) {
  return typeof curr !== "undefined" ? prev+1 : prev;
}, 0); // evaluates to 4

reduce() is supported by all modern browsers, IE9+. For older browsers there's a polyfill and more info over at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Upvotes: 2

Robert Harvey
Robert Harvey

Reputation: 180858

John Resig (author of jQuery) wrote a function that (really) removes items from an array in Javascript. If you use this function instead of the delete operator, you should get an accurate count from the array after the deletion.

http://ejohn.org/blog/javascript-array-remove/

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827606

I think that you are deleting your array elements by using the delete operator.

This operator removes the element at the index you specify, but the array length is not affected, for example:

var a = [1,2,3];

delete a[0];

console.log(a); // results in [undefined, 2, 3] 

If you want to delete the elements and shift the indexes, you can use the splice function:

var a = [1,2,3];

a.splice(0,1);

console.log(a); // [2, 3]

You could implement a simple function to remove elements in a given index:

Array.prototype.removeAt = function (index) {
  this.splice(index,1);
};

Upvotes: 14

Related Questions