Treehouse

Implementing an Array.count() Method in JavaScript

By on  

As much as I write about MooTools on my blog, I spend most of my work day knee-deep in PHP. As you probably know, one way to get the size of an array in PHP is to use the count() function:

echo count($my_array);

In JavaScript, the way to get the size of an array is to use the length property, like this:

alert(my_array.length);

For some reason, I absolutely hate the ".length" way of retrieving the length of an array. For this reason, I've implement the count() method into JavaScript:

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

The count() habit is difficult to break, so why try?

ydkjs-3.png

Recent Features

  • Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating:

  • 5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our...

  • An Interview with Eric Meyer

    I've always wanted to interview Eric Meyer. His early CSS books are a big reason this blog exists today and the reason why I'm a web developer. Eric gave me some time to hit the history of CSS,...

Incredible Demos

  • Scroll IFRAMEs on iOS

    For the longest time, developers were frustrated by elements with overflow not being scrollable within the page of iOS Safari.  For my blog it was particularly frustrating because I display my demos in sandboxed IFRAMEs on top of the article itself, so...

  • Custom Scrollbars in WebKit

    Before each of the browser vendors we like was providing unique CSS controls, Internet Explorer was setting the tone.  One such example is IE's early implementation of CSS filters. Internet Explorer was also the first browser that allowed developers...

  • Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of...

Discussion

  1. Thanks for your blog. you offer great advice and tutorials and for some odd reason, if I am looking to see how to complete a task, you have a tutorial on it or at least an idea on the concept I am trying to achieve; so thanks David. Although this post came about 2 days too late. :)

  2. Do you do this for strings as well?

  3. @Binny: No, I don’t. Just arrays.

  4. Jason

    This is all fine and well, but length is fundamentally different from count.

    Take the following example:

    var myArray = ['one', 'two', 'three'];
    // myArray.length == 3, as we would expect

    var myOtherArray[100] = ‘one’;
    //myArray.length == 100, NOT 1

    Even though we only have 1 item in the array, ‘length’ refers to the largest index + 1. Unlike PHP where we can use numeric keys and strings for indexes in an ad hoc way and still get an accurate count via count(), in JS it’s not quite the same.

    In a way, this is just splitting hairs, but a lot of people already don’t understand JS’s length property, and referring to it as “count” only serves to further the confusion.

  5. Jason

    Correction to my previous post:

    the second code snippet would be:

    var myOtherArray = [];
    myOtherArray[100] = ‘one’;

    and its length property would actually return 101.

  6. riv

    That’s right and that’s what I was expecting when searching for count on js. This should do it:

    function count(array)
    {
        var c = 0;
        for(i in array) // in returns key, not object
            if(array[i] != undefined)
                c++;
    
    return c;
    }
    
    • Riv, thats a much better form of the count use. Its surprising that this is not built into javascript.

  7. Christian

    Array.prototype.count = function () {
    for (k in this) { if (this[k].constructor !== Function) { this.length++; } };
    return this.length;
    }

  8. I think it’s okay for personal project but it has a counter side when you are in enterprise. The maintainability is harder when people use custom extension (prototype existing framework object). It cane be confusing. In some case, I have seen people creating function to simply get an object inside an array. I think this should be used with parsimony. But, it’s just my opinion…

  9. Iskren Antonov
    Array.prototype.count = function () {
    	var counter = 0; // Initializing main counter
    	for(i in this) // Looping through elements
    		if(typeof this[i] != "undefined") // If empty it's undefined
    			counter++; // Counting not empty elements
    	return counter-1; // Excepting own function
    }
    

    This is a working one. It counts function elements too.

  10. Lineo

    I’ve just bumped into learning Js, I try to be as attentive as possible but, I don’t find a way. So, may any one help me how to understand Js programming.

  11. Rowan Adinghey
    Array.prototype.count = function (a) {
    	var c = 0;
    	for(var i = 0; i < this.length; i++) {
    		if(typeof(this[i]) !== "undefined") {
    			if(typeof(this[i]) == "string" && this[i].length == 0) {
    			} else { 
    				c++;
    			}
    		}
    	}
    	return c;
    }
    

    OR

    
    count = function (a) {
    	var c = 0;
    	for(var i = 0; i < this.length; i++) {
    		if(typeof(a[i]) !== "undefined") {
    			if(typeof(a[i]) == "string" && a[i].length == 0) {
    			} else { 
    				c++;
    			}
    		}
    	}
    	return c;
    }
    

    Wow, no functionality to edit comments? What is this, the year 2001?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Use Code Editor