Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 877
Lobe Avatar asked Oct 15 '09 04:10

Lobe


3 Answers

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);
};
like image 63
Christian C. Salvadó Avatar answered Sep 30 '22 14:09

Christian C. Salvadó


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

like image 27
tobek Avatar answered Sep 30 '22 15:09

tobek


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
like image 29
Paweł Avatar answered Sep 30 '22 15:09

Paweł