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.
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:
!(+el % 1)
which check if el
can be considered as numerical property even if it has a type of string.
+el>=0
+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
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With