Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of elements of an array in javascript

Tags:

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?

like image 975
Latheesan Avatar asked Sep 08 '16 18:09

Latheesan


2 Answers

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

const answers = [];

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

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

console.log(Object.keys(answers).length); // prints 2
like image 118
SimpleJ Avatar answered Oct 07 '22 18:10

SimpleJ


You can simply use Array#filter method which doesn't iterate over deleted or undefined array elements.

answers.filter(function(v){ return true; }).length

var answers = [];

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

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

console.log(answers.filter(function(v) {
  return true;
}).length);
like image 3
Pranav C Balan Avatar answered Oct 07 '22 19:10

Pranav C Balan