Skip to content
Advertisements

Array map()

JavaScript Array map() Definition

The Map () method scans through each element of the array. It returns a new array with the elements it scans. The map() method calls the provided function once for each element in an array, in order. The map () method does not change the array, like other methods.

Syntax:

array.map(function(currentValue, index, arr), thisValue)

current(ValueRequired): We enter the value of the current element here.
index(Optional): We’re entering the index of the current directory.
arr(Optional): The array object the element belongs to.


Let’s try to figure out what it does with a small sample:

        let coffees = ["Flat White", "Caramel Macchiato", "Caffè Americano", "Espresso"];
        let buyCoffee = coffees.map(function (coffees) {
            return "coffee type:" + coffees;
        })
        console.log(buyCoffee)

0: “coffee type:Flat White”
1: “coffee type:Caramel Macchiato”
2: “coffee type:Caffè Americano”
3: “coffee type:Espresso”

Here it scans the elements in the array individually. Applies the function we specify to the elements scanned.


Array map VS Array forEach

foreach(): This iterates over a list and applies some operation with side effects to each list member (example: saving every list item to the database)

map(): This iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (example: transforming list of strings to uppercase).

In other words: forEach doesn’t actually return anything. It just calls the function forEach array element and then it’s done. So whatever you return within that called function is simply discarded.

On the other hand, map will similarly call the function forEach array element but instead of discarding its return value, it will capture it and build a new array of those return values.

If you want to know more about forEach (). Click


JavaScript Array map() Examples

Example 1

        let numbers = [ 2, 3, 4, 5 ]
        function process(x) {
            return x * x;
        }
        console.log(numbers.map(process))

output:

[4, 9, 16, 25]


Example 2

        var coffees = [
          { name: "Caramel Macchiato", type: "(hot)" },
          { name: "Flat White", type: "(hot)" },
          { name: "Caffè Mocha", type: "(cold)" },
          { name: "Caramel Macchiato", type: "(cold)" }
        ];
            

        function coffeeType(a, b) {
            var x = [a.name, a.type].join("");
            return x;
        }

        console.log(coffees.map(coffeeType))
       

output:

“Caramel Macchiato(hot)”
“Flat White(hot)”
“Caffè Mocha(cold)”
“Caramel Macchiato(cold)”


Example 3

        let number = ["first","second","third"];
        let dog = number.map(() => {
            return 'dog';
        });

        console.log(dog)

output:

[“dog”, “dog”, “dog”]


Example 4

        let number1 = (Math.floor(Math.random() * 10));
        let number2 = (Math.floor(Math.random() * 10));
        let number3 = (Math.floor(Math.random() * 10));
        let number4 = (Math.floor(Math.random() * 10));

        let list = [number1, number2, number3, number4]
        
        let process = list.map((x) => {
            if (x % 2 == 0) {
                return x
            }
        })

        console.log(process);

output:

[6, 0, undefined, 8]


Polyfill

if (!Array.prototype.map) {

  Array.prototype.map = function(callback/*, thisArg*/) {

    var T, A, k;

    if (this == null) {
      throw new TypeError('this is null or not defined');
    }

    // 1. Let O be the result of calling ToObject passing the |this| 
    //    value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal 
    //    method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if (arguments.length > 1) {
      T = arguments[1];
    }

    // 6. Let A be a new array created as if by the expression new Array(len) 
    //    where Array is the standard built-in constructor with that name and 
    //    len is the value of len.
    A = new Array(len);

    // 7. Let k be 0
    k = 0;

    // 8. Repeat, while k < len
    while (k < len) {

      var kValue, mappedValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal 
      //    method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal 
        //    method of O with argument Pk.
        kValue = O[k];

        // ii. Let mappedValue be the result of calling the Call internal 
        //     method of callback with T as the this value and argument 
        //     list containing kValue, k, and O.
        mappedValue = callback.call(T, kValue, k, O);

        // iii. Call the DefineOwnProperty internal method of A with arguments
        // Pk, Property Descriptor
        // { Value: mappedValue,
        //   Writable: true,
        //   Enumerable: true,
        //   Configurable: true },
        // and false.

        // In browsers that support Object.defineProperty, use the following:
        // Object.defineProperty(A, k, {
        //   value: mappedValue,
        //   writable: true,
        //   enumerable: true,
        //   configurable: true
        // });

        // For best browser support, use the following:
        A[k] = mappedValue;
      }
      // d. Increase k by 1.
      k++;
    }

    // 9. return A
    return A;
  };
}

Browser Support

Chromeyes
Edgeyes
Firefox1.5
Internet Explorer9
Operayes
Safariyes
Android webviewyes
Chrome for Androidyes
Edge mobileyes
Firefox for Android4
Opera Androidyes
Advertisements

2 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: