Javascript array count method

Hi Guys,

So for the project I am working on I am using both PHP and Javascript.

Now I got a habit of using count() method in PHP for array to count the number of element in an Array.

You can use length property of an Array in Javascript but I like it the PHP way so then I wrote these few lines of code to accomplish that

So traditionally in PHP we use something like this

PHP Pseudo Code

  1. if(count($myArray)>0) {
  2.    // do this
  3. } 
  4. else {
  5. //  do that 
  6. }

This is A way to use count method but its used at many different places for different use cases.

Now lets see whats the Javascript equivalent


Advertisement

 

Javascript Count() method

So say we have a Javascript array as shown below

  1. var myArray = [1,2,3,4,5]

I can get the count of array elements by simply doing this

  1. console.log(myArray.length)

Above will print 5

Thats good. I mean there is no real advantage of having a count() method but lets see how to do a count() method for an array. Now just return a length property may just not be enough to get what you want (an actual count of elements)

  1. Array.prototype.count = function() {
  2.     return this.length;
  3. };

A much better approach would be the one below and the one that I will use.

  1. Array.prototype.count = function() {
  2.     var cnt = 0;
  3. for(k in this) {
  4. if(this[k] != undefined) {
  5. cnt++;
  6. }
  7. }
  8. return cnt>0?cnt-1:0;
  9. };

Above approach will handle cases like this one

  1. mas = [];
  2. mas[23] = 23;
  3. console.log(mas.count()); // will return 1 rather than 24

Now when you do this

  1. console.log(myArray.count());

Above  will print 5

For me I don’t think that length in Javascript is true length of an array. But in most cases it does the trick.

You can do the same for extending default behaviour for any known Javascript class.

I hope this helps

Cheers

 P.S. :  Its always a good idea to keep your custom methods in your standalone object rather to extend native objects. That’s my opinion.

Advertisement

 

 

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Speak Your Mind

*

CommentLuv badge