Free, tested & ready to use examples!
AnyExample.com
 
Web anyexample.com
 


AnyFormat.io - convert files and webpages to any format!

JavaScript Array map function

abstract 
Array.prototype.map() function allows you to create a new array by transforming the existing one by calling a function on each element of the original array.
compatible 
  • Chrome
  • Firefox
  • Opera
  • Safari
  • IE9+
  • So you have an array of numbers in JS. What you want to get is an array of cubes for those:

    var arr = [1, 2, 3]; // original array
    
    var cubes = arr.map(function(el){
      return el * el * el;
    });
    // now 'cubes' is [1, 8, 27]
    

    Easy right? :) But what if you want to make a function that capitalizes any string it gets?
    You can use String.prototype.toUpperCase() for one string, but if you need to pass lots of string and capitalize them? Use arguments array to do this!

    function capitalize(a) {
      if (arguments.length === 1) {
        return a.toUpperCase();
      } else {
        return arguments.map(function(el) { return el.toUpperCase(); });
      }
    }
    
    console.log(capitalize('my', 'name', 'is', 'Jack'));
    

    Whoops! TypeError: undefined is not a function says the browser!
    The problem relies in arguments object. It's not a 'real' Array even if it pretends to be. But we can solve this by calling Array.prototype.map on it generically:

    function capitalize(a) {
      if (arguments.length === 1) {
        return a.toUpperCase();
      } else {
        return Array.prototype.map.call(arguments, function(el) { return el.toUpperCase(); });
      }
    }
    
    console.log(capitalize('my', 'name', 'is', 'Jack')); // outputs ["MY", "NAME", "IS", "JACK"] to console
    console.log(capitalize('my')); // "MY"
    console.log(capitalize()); // []
    

    Note that you can call map() function on arguments object also like this:

    ...
    [].map.call(arguments, function(el) { ... });
    ...
    

    Looks a bit better and shorter :)
    Go on experimenting with map() function on your arrays!

    warning 
  • Use es5-shim for IE8 support
  • tested 
  • Chrome, Firefox
  •  


     
    © AnyExample 2010-2013
    License | Privacy | Contact