Array Extras

With the upcoming Firefox 1.1 release (and other browsers based on Gecko 1.8) things are starting to move in javascript land. During the early years of javascript a lot happend but then came the ambitious plans ofJS2 and the improvements to js just kind of died away for no reason. It seems Mozilla is finally taking some actions in this field and they’ve added a few very useful methods to Array:

Since not everyone is running nightly builds (or Deer Park alpha 1) I’m now providing these methods for anyone who finds them interesting.

I’ve also added the following useful methods. These greatly benefits from the native implementation of indexOf:

  • contains
  • copy
  • insertAt
  • insertBefore
  • removeAt
  • remove

25 Responses to “Array Extras”

  1. Emil Says:

    That indexOf method will prove quite useful.
    Nice to see updates to the JavaScript language (implementation) again.

  2. M. Schopman Says:

    I hope to see more improvements in future, according to specifications. I have seen an ECMA specification once (dunno if it was a draft or final) where they talked about full support for private/public/protected/virtual/constructors/destructors/classes etc. Such would really improve the acceptance as Javascript as a real language for fat client development.

  3. Erik Arvidsson Says:

    Micha: See the JS2 link in the first paragraph.

  4. Geoff Moller Says:

    Many thanks for posting the external implementation. Extremely handy :)

  5. Mark Wubben Says:

    Thanks for the update. The link to the docs for ‘every’ is broken, though :)

  6. David Flanagan Says:

    The functions other than indexOf() and lastIndexOf() are getting moved to Function.prototype instead of Array.prototype.

    See https://bugzilla.mozilla.org/show_bug.cgi?id=304828

  7. David Flanagan Says:

    I recently proposed an Array.prototype.append() method at my own blog.
    One of the commenters complained that adding enumerable properties to Array.prototype will break any code that uses for/in on an array.

    This argument is very true for Object.prototype: we really can’t add method there. But I’d never heard it expressed for Array.prototype. It is true that one can use for/in to iterate through the indexes of an array. But does anyone actually do this? If someone does this do they deserve to have their code break?

  8. David Flanagan Says:

    I have to keep submitting comments because I love the little popup that appears to show me that my comment has been added at the bottom!

  9. Nick Van Weerdenburg Says:

    After the last comment, I need to add a comment.

  10. Erik Arvidsson Says:

    David: Thanks for pointing me to that Bugzilla bug. Lot’s of interesting stuff going on there.

    Using a for in loop to loop over an array is incorrect and error prone. It is not too uncommon to see people use it and it shows that people are not aware that it does not really work. See http://erik.eae.net/archives/2005/06/06/22.13.54/#comment-5132

  11. erik’s weblog » Blog Archive » JS Generics Says:

    [...] ;ve become too used to them to survive long without them. I’ve previously posted the JS 1.5 array extras and I’ve also mentioned these methods but now I’ve implemented [...]

  12. Jeoff Hines Says:

    You use the for…in to find the keys in a hash array:
    var a = new Array();
    a["key1"] = “test”;
    a["key2"] = “test”;

    for(var key in a)
    alert(key);

    will show you “key1″ and “key2″. If you add prototypes to Array it will show the names of those functions too and thus break the for/in. I use associative arrays a lot (I like strings) so this is very important to me. If you can think of another way to extract the keys from an associative array then please elucidate because I would love to know! Otherwise, you should leave the built-in objects alone I think.

  13. Erik Arvidsson Says:

    Jeoff: Why are you using an Array here? The feature you want is a feature of Object, which Array extends. It is equally correct/incorrect to use a RegExp as an Array.

    Correct?:

    var a = new RegExp();
    a[”key1″] = “test”;
    a[”key2″] = “test”;

    for(var key in a)
    alert(key);

    Correct!:

    var a = {};
    a[”key1″] = “test”;
    a[”key2″] = “test”;

    for(var key in a)
    alert(key);

  14. Dan Dean Says:

    Hi Erik,
    Thanks for putting this together and releasing, I find it very useful.

    A note regarding IE5 compatability (yes, I should probably forget about IE5!): I’ve found some good Function.call() and Function.apply() methods at http://www.browserland.org/scripts/dragdrop/. With the addition of these, all of the above methods seem to work in IE5, as long as this is added to the beginning of each that utilize f.call()

    var obj = (obj != null) ? obj : this;

    Do you see any problems with the addition of this?

  15. Erik Arvidsson Says:

    Dan: Yes, that would be wrong. If obj is not passed it is supposed to use [[Global]] (or window in a browser context) as the value for this.

    I do not care about JScript 5 (shipped with IE50). It has so many ECMAScript bugs that it is ridicilus and it is holding back development in a lot of scenarios. You would be doing yourself a favor in not supporting it and getting users onto something better and more secure.

    (The same applies to Safari before like the current nightly build and I suggest not supporting anything but the latest version of Safari.)

  16. Thomas Frank Says:

    Brilliant! Thanks!

  17. Johan Sundström Says:

    More of a reflection than suggestion: testing for Array.prototype.forEach and friends this way rather than by way of Array.prototype.hasOwnProperty(’forEach’) will find Object.prototype.forEach when no Array specific implementation exists. This is probably still often what you want, assuming that the Object prototype internally handles different data types differently in sane manners, but once in a while it might not be.

  18. Jeff Walden Says:

    Your code for Array.prototype.lastIndexOf has a bug in it: when the second argument is a negative number and the sum of that argument and the array’s length is less than zero, you might erroneously return 0 when searching for the first element in the array. For example:

    [2].lastIndexOf(2, -5)

    …will return 0 with your code, when according to the function’s description it should return -1. The fix should be to replace |Math.max(0, this.length + fromIndex)| with |this.length + fromIndex| in the lastIndexOf implementation.

    Also, don’t bother testing behavior in Firefox, because Firefox has this bug (and an indexOf bug which is a little harder to duplicate). I’m checking whether non-Firefox implementations demonstrate this and the other bug to evaluate how feasible it is to fix this behavior in point releases to stable Firefox versions. (The bug is https://bugzilla.mozilla.org/show_bug.cgi?id=364104 if you’re interested.)

  19. Jeff Walden Says:

    Actually, let me backtrack for a second — I’m not sure the docs I was referencing were canonical. I’ll get back with more details later…

  20. Jan van Casteren Says:

    Thank you for this handy script. One question: is there any reason to have the obj parameter in the copy method?

    See:

    Array.prototype.copy = function (obj) {
    return this.concat();
    };

  21. Erik Arvidsson Says:

    Jan: That is just a typo. You should remove that.

  22. Ajaxian » JavaScript Scripting Essentials Says:

    [...] Dan Webb asks what are your JavaScript essentials? Those bits and pieces you can’t live without that get copy/pasted from project to project. His pragmatic list includes the $ function, getElementsByClassName, Dean’s event handling, the JS 1.6 array methods, and the DOMContentLoaded event. His full script that he guarantees he _won’t_ support is here. [...]

  23. Scripting Essentials » Professional Web Software Development Says:

    [...] Javascript’s new forEach() function. Thanks to Dean Edwards, there is a cross browser solution, that is extremely simple to use. There are some other new functions as well that I haven’t explored yet, but they are worth noting. [...]

  24. JavaScript Scripting Essentials Says:

    [...] Dan Webb asks what are your JavaScript essentials? Those bits and pieces you can’t live without that get copy/pasted from project to project. His pragmatic list includes the $ function, getElementsByClassName, Dean’s event handling, the JS 1.6 array methods, and the DOMContentLoaded event. His full script that he guarantees he _won’t_ support is here. [...]

  25. Patrick Kwinten Says:

    thanks for the help, I had some problem with using prototype and defining arrays, some how using

    var tagMap= new Array()

    causes that prototype adds other elements to the array :-?

Leave a Reply