« Visual C# Express Sucks | Main | Object.prototype is verboten »

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:

  • indexOf
  • lastIndexOf
  • forEach
  • filter
  • map
  • some
  • every

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

This entry was posted on Sunday, June 5th, 2005 at 17:53 and is filed under JavaScript, Web. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

26 Responses to “Array Extras”

  1. Emil Says:
    June 6th, 2005 at 16:44

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

  2. M. Schopman Says:
    June 9th, 2005 at 20:27

    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:
    June 10th, 2005 at 23:58

    Micha: See the JS2 link in the first paragraph.

  4. Geoff Moller Says:
    June 14th, 2005 at 19:33

    Many thanks for posting the external implementation. Extremely handy spacer

  5. Mark Wubben Says:
    June 23rd, 2005 at 10:12

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

  6. David Flanagan Says:
    August 17th, 2005 at 00:26

    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:
    August 17th, 2005 at 00:31

    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:
    August 17th, 2005 at 00:38

    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:
    August 18th, 2005 at 21:57

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

  10. Erik Arvidsson Says:
    August 20th, 2005 at 17:06

    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 erik.eae.net/archives/2005/06/06/22.13.54/#comment-5132

  11. erik’s weblog » Blog Archive » JS Generics Says:
    February 28th, 2006 at 00:41

    [...] ;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:
    April 17th, 2006 at 09:21

    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:
    April 17th, 2006 at 20:34

    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:
    April 21st, 2006 at 12:11

    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 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:
    April 24th, 2006 at 08:58

    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:
    July 14th, 2006 at 05:00

    Brilliant! Thanks!

  17. Johan Sundström Says:
    November 5th, 2006 at 04:30

    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:
    December 17th, 2006 at 08:12

    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:
    December 17th, 2006 at 08:17

    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:
    December 18th, 2006 at 08:58

    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:
    December 26th, 2006 at 14:55

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

  22. Ajaxian » JavaScript Scripting Essentials Says:
    January 14th, 2007 at 15:48

    [...] 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:
    January 23rd, 2007 at 14:01

    [...] 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:
    March 1st, 2007 at 04:16

    [...] 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:
    March 26th, 2008 at 07:41

    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 spacer

  26. NCZOnline » Blog Archive » Mozilla’s new Array methods Says:
    August 30th, 2008 at 22:48

    [...] caught this post over at Erik’s regarding the new additions to the Array object available in Firefox 1.1. The [...]

Leave a Reply

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.