11

This will sound a very silly question. How can we find the exact length of array in JavaScript; more precisely i want to find the total positions occupied in the array.

I have a simple scenario which i guess most of you might be aware of.

var a = [1,2,3];
a.length; //This will output 3

Now if i give

a[100] = 100;
a.length; // The output is 101; 

I want to get the exact size of the array which in the above case should be 4.

Yameen
  • 585
  • 1
  • 6
  • 17
  • check for the first undefined value if the array is filled in incremental order. – lateralus Mar 02 '15 at 14:15
  • 1
    do a for loop and increment counter other than `undefined` – Rakesh_Kumar Mar 02 '15 at 14:15
  • 1
    In Javascript arrays are not created with bounded length, so when you do a[0] = 1; a[100] = 100, length becomes `101`. One thing you can do is loop from 0 -> array.length and keep track of values which are not `undefined` – Arkantos Mar 02 '15 at 14:18
  • 1
    @Rakesh_Kumar do you mean something like this for (i= 0 ; a[i] != undefined || a[i] != null ;i++); but this wont work in our case. As it will stop the loop at index = 3; – Yameen Mar 02 '15 at 14:19
  • 1
    @Yameen http://jsfiddle.net/kwu3xqsm/ – Rakesh_Kumar Mar 02 '15 at 14:20
  • 1
    Why are you creating an array with holes if you don't seem to want an array with holes? – Felix Kling Mar 02 '15 at 14:40

4 Answers4

24

What you are looking for is not the length of an array but the number values allocated in that array.

Array.length will NOT give you that result but the total number of values allocated.

A workarround is to count the properties of the object behind the array, with:

Object.keys(a).length

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Relationship_between_length_and_numerical_properties

But with some caveats:

  • It will also count literal properties, like a.a_property. I do not think that is what you want. So, you will have to filter that result:

!(+el % 1) which check if el can be considered as numerical property even if it has a type of string.

  • you want count only positive integers, so you have to filter them with:

+el>=0

  • finally, as array size is limited to 2^32, you will to also filter positive integers greater than that:

+el < Math.pow(2,32)

Functionally, you will have your result with this filter:

Array.realLength= Object.keys(a).filter(function(el){return !(+el % 1) && +el>=0 && +el < Math.pow(2,32) ;}).length 
Gaël Barbin
  • 3,769
  • 3
  • 25
  • 52
5

TL;DR The simplest reliable approach that I can think of is the following:

var count = a.filter(function() { return true; }).length;

In modern JavaScript engines, this could be shortened to:

var count = a.filter(() => true).length;


Full answer:

Checking against undefined isn't enough because the array could actually contain undefined values.

Reliable ways to find the number of elements are...

Use the in operator:

var count = 0;
for (var i = 0; i < a.length; i += 1) {
    if (i in a) {
        count += 1;
    }
}

use .forEach() (which basically uses in under the hood):

var a = [1, undefined, null, 7];
a[50] = undefined;
a[90] = 10;

var count = 0;
a.forEach(function () {
    count += 1;
});

console.log(count);    // 6

or use .filter() with a predicate that is always true:

var a = [1, undefined, null, 7];
a[50] = undefined;
a[90] = 10;

var count = a.filter(function () { return true; }).length;

console.log(count);    // 6
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • That's why we don't check for `undefined`. We check if it's NOT undefined and increment some counter in that case and repeat this from 0 -> array length :) – Arkantos Mar 02 '15 at 14:27
  • @Arkantos Checking that each element is not `undefined` can yield a count that is lower than the actual number of elements, and that is exactly my point. – JLRishe Mar 02 '15 at 14:30
  • Oops my mistake.. I was talking in the context of the OP's array where he has only integers in his array :) – Arkantos Mar 02 '15 at 14:35
0

the size of the array is exactly what is shown by the length property.

even though you gave a value only to the first 3 positions(0,1,2), when you gave the value 100 to the a[100], you resized it to 101 positions. Therefore, you'll get the count of every position, from 0(first index) to 100(last index), even if they have no value.

0

With your code: a[100] = 100, you are creating a block at location 100 in your array. (Total of 101 since it starts at 0).

If you want to see how many actual answers are in the block you would have to use a loop and cycle through checking which fields are not equal to undefined. There are dozens of ways to do this with for, while, foreach, etc.

Just implement a counter and count the sections in the array that are not equal to null or undefined. That will give you the number of places that are actually being used in the array.

Knut Holm
  • 3,988
  • 4
  • 32
  • 54
jscroggs
  • 3
  • 4