JAVA SCRIPT - Applying a Function to Every Element in an Array and Returning a New Array

Applying a Function to Every Element in an Array and Returning a New Array


Problem

You want to convert an array of decimal numbers into a new array with their hexadec‐ imal equivalents.


Solution


Use the Array map() method to create a new array consisting of elements from the old array that have been modified via a callback function passed to the method:



var decArray = [23, 255, 122, 5, 16, 99];
var hexArray = decArray.map(function(element) {
 return element.toString(16);
});
console.log(hexArray); // ["17", "ff", "7a", "5", "10", "63"]


EXPLAIN 

Like the forEach() method in Recipe 2.5, the map() method applies a callback function to each array element. Unlike forEach(), though, the map() method results in a new array rather than modifying the original array. You don’t return a value when using forEach(), but you must return a value when using map(). The function that’s passed to the map() method has three parameters: the current array element, and, optionally, the array index and array. Only the first is required.

0 comments:

Post a Comment