Pranesh Ravi Pranesh Ravi - 2 months ago 22
Javascript Question

Length of sparse arrays

[UPDATE]: Got the solution. Going to use

lodash.compact([]).length


I'm having an array will take n values, but the values will be added to different index at different time. But, I need the length of the array at a particular time.

Case 1

var a = [1,2,3,3,4]

a.length //Returns 5


Case 2

var a =[]
a[20] = 2 //I want to have 2 in the 20th index
a.length //Returns 21


I know the remaining element(0-19) in the array
a
will be
undefined
.

How to get the length as
1
for the case 2?

Answer

If you can use underscore. You may try like this

var arrLen = _.compact(youArr).length;

If you want to use pure JS..you will need to write simple function. That will count number of elements not equal to false.

var len = 0;
arr.forEach(function(el){
  if (el) {count++;}
});
console.log(len);

Hope this helps.