Latheesan Latheesan - 2 months ago 7
Javascript Question

Count the number of elements of an array in javascript

Consider the following:

var answers = [];

answers[71] = {
field: 'value'
};

answers[31] = {
field: 'value'
};

console.log(answers);


This outputs the length of the array as 72 but I was expecting it to return 2. Here's the output of the script from chrome console:

enter image description here

Any ideas why this is?

Answer

You can count the actual number of keys using Object.keys(arr).length:

var answers = [];

answers[71] = {
    field: 'value'
};

answers[31] = {
    field: 'value'
};

console.log(Object.keys(answers).length); // prints 2