Pranesh Ravi Pranesh Ravi - 1 year ago 99
Javascript Question

Length of sparse arrays

[UPDATE]: Got the solution. Going to use


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
will be

How to get the length as
for the case 2?

Answer Source

If you can use underscore. You may try like this

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

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

var len = 0;
  if (el) {count++;}

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download