Take the 2-minute tour ×

Is it possible to get length of an array without iterating complete array having non numeric indexes?

Length property is always 0 for non numeric indexed array.

Can we get number of elements using another property of array or it's prototype?

var arr = [];
arr['first'] = 1;
arr['second'] = 2;
console.log(arr.length); //0
share|improve this question
It's not an array, it's just an object with properties. arr['first'] is the same as arr.first. Also a dupe of this question, which can help you: stackoverflow.com/questions/5223/… –  bhamlin Mar 12 '12 at 18:45
add comment

2 Answers

up vote 4 down vote accepted

Arrays are meant for numeric indices.

You can add other properties, but they have no impact on the length, and the methods of Array.prototype will ignore them.

If you're using non-numeric properties, you should be using {} (an Object), and you'll need to maintain your own .length.

Alternately, you could use the Object.keys method to find out how many properties there are...

var obj = {};
obj['first'] = 1;
obj['second'] = 2;

var n = Object.keys(obj).length; // 2

For browsers that don't support ECMAScript 5, you'll need a compatibility patch...

share|improve this answer
add comment

Okay so the problem is you are not adding values to the array, you're adding properties to the object. As far as getting the number of native properties for an object you can use the Object.keys(arr).length

share|improve this answer
add comment

Your Answer


