Saturday 15 September 2018

JavaScript: map: Return new array by applying function on every element of the array

map method returns new array with the results of calling a provided function on every element in this array.

Syntax
arr.map(callback[, thisArg])

callback is a function that takes following three arguments.
Argument
Description
currentValue
The current element being processed in the array.
index
The index of the current element being processed in the array.
array
The array that map() is being applied to.

thisArg
Optional. Value to use as this when executing callback.

Get new array by squaring element
/* Get new array by squaring every element */
var arr2 = arr1.map(function(value){
         return value * value
});

Get new array by applying square root
var arr3 = arr1.map(Math.sqrt);

map.html
<!DOCTYPE html>

<html>

<head>
    <title>Array map</title>
</head>

<body>
    <script type="text/javascript">
        var arr1 = [2, 3, 5, 7];
        displayArray(arr1);

        /* Get new array by squaring every element */
        var arr2 = arr1.map(function(value) {
            return value * value
        });
        displayArray(arr2);

        /* Get new array by applying square root on every element */
        var arr3 = arr1.map(Math.sqrt);
        displayArray(arr3);

        function displayArray(array, arrayName) {
            document.write("<br />Elements in array " + arrayName + " are <br />");

            array.forEach(function(value) {
                document.write(value + "<br />");
            });
        }
    </script>
</body>

</html>


Previous                                                 Next                                                 Home

No comments:

Post a Comment