1

How do I get the number of elements in an array with non-consecutive numbers as keys?

var array = [];  
array[5] = "something";  
array[10] = "nothing":  

expected:
number of elements in array = 2

actual:
instead I get the last number used as the "length", 11

I can figure out the way to do this by iterating through each element. Is there is better way to do this?

agent provocateur
  • 747
  • 3
  • 13
  • 38
  • 1
    __NO__, Array has indexes starting from `0`, if you assign some value at index `n`, length of array will be `Maximum value of n + 1` – Rayon Aug 10 '16 at 17:49
  • Note that `length` will be __`11`__, not _`10`_ – Rayon Aug 10 '16 at 17:50
  • Possible duplicate of [How best to do a JavaScript array with non-consecutive indexes?](http://stackoverflow.com/questions/4771001/how-best-to-do-a-javascript-array-with-non-consecutive-indexes) – Heretic Monkey Aug 10 '16 at 17:52
  • Possible duplicate of [How to efficiently count the number of keys/properties of an object in JavaScript?](http://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip) – 4castle Aug 10 '16 at 17:59

4 Answers4

2

You may count non empty cells:

array.filter(function(e){return e!==undefined}).length
Oleg Imanilov
  • 2,268
  • 1
  • 11
  • 21
  • I think your method is the best, though `array.filter(Boolean)` would be more concise. Also, could you explain your answer a bit more? – Rob M. Aug 10 '16 at 17:58
  • @RobM. What is `Boolean`? – 4castle Aug 10 '16 at 18:00
  • @4castle it's the object wrapper around Boolean values ([link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)). In `filter` calls it can serve as an identity function though, testing for truthy values – Rob M. Aug 10 '16 at 18:03
  • @RobM. Ahh, nifty. It would work in this case perhaps, but it would also filter out `0` and `""`, which may be valid values. – 4castle Aug 10 '16 at 18:06
  • @Nosyara correct. Definitely not applicable for all use cases, but based on the data OP posted I think it works here. – Rob M. Aug 10 '16 at 18:09
0

Sounds like what you actually want is a dictionary, not an array. Have you considered that as an alternative data structure?

How to do associative array/hashing in JavaScript

var myArray = {};
myArray["5"] = "something";
myArray["10"] = "nothing";

And to get the length you would want to write a quick function like the one shown here:

Length of a JavaScript object

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

var size = Object.size(myArray);

Or alternatively, even simpler (but not supported by IE8):

Object.keys(myArray).length
Community
  • 1
  • 1
sage88
  • 3,208
  • 3
  • 27
  • 36
  • [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) might make more sense, as it is a native implementation of your code (and contains a `size` property) – Rob M. Aug 10 '16 at 18:07
  • @RobM. Yeah using a Set.prototype would be a great way to solve this problem as well and would be more resource efficient. – sage88 Aug 10 '16 at 18:10
  • 2
    Seeing as the indexes are probably important, I think a `Map` is closer. `Set` and `Map` have low browser support still though. – 4castle Aug 10 '16 at 18:13
  • @4castle I was just about to comment that that, "hold on, actually set loses the key" so yeah it sounds like the keys are important so Map would be better, and the implementation above is probably more likely to be supported than Map. – sage88 Aug 10 '16 at 18:15
0
var array = [];  
array[5] = "something";  
array[10] = "nothing": 

Your array in this case becomes :

[undefined,undefined,undefined,undefined,undefined,"something",undefined,undefined,undefined,undefined,"nothing"]

thats why the length is coming as 11. So ideally you should not set it like array[5] or array[10].

If you have variable keys, then you should use object

a = {};    
a["5"] = "something";
a["10"] = "nothing"

Then a will look like {"5":"something","10":"nothing"}

Then you can calculate count as :

var elemCount = 0;
for(var key in a){
elemCount++;
}

Output:

elemCount = 2

Various other ways of getting length of keys in object: How to efficiently count the number of keys/properties of an object in JavaScript?

Community
  • 1
  • 1
abhinsit
  • 2,962
  • 4
  • 16
  • 24
-1

var array= Array(5);
array[1] = 10;
array[3] = 3;

numberOfElements = 0;

for(var i  =0; i<array.length; i++) {
 if(array[i]!=undefined)
  numberOfElements++;
}
alert(numberOfElements);
Aleksandar Đokić
  • 1,551
  • 11
  • 30