Example of Javascript Array Map

Here, we will discuss the example of a Javascript Array Map. Reading implementations is a critical component of comprehension. So, to better comprehend what’s going on beneath the hood, let’s create our own lightweight map. If you want to see a production-quality implementation, go no further.

Implementation Map & Syntax

let map = function (array, callback) {
  const new_array = [];
 
  array.forEach(function (element, index, array) {
    new_array.push(callback(element));
  });
 
  return new_array;
};

As parameters, this code takes an array and a callback function. It then generates a new array, runs the callback on each member of the array we provided in, pushes the results into the new array, and returns it. You’ll receive the same result if you run this in your console as previously.

While we’re still using a for loop below, wrapping it up into a function hides the mechanics and allows us to focus on the abstraction.

This makes our code more declarative—it tells us what to do rather than how to accomplish it. You’ll enjoy how much more legible, manageable, and, uh, debuggable your code becomes as a result.

Example

const persons = [
  {firstname : "Malcom", lastname: "Reynolds"},
  {firstname : "Kaylee", lastname: "Frye"},
  {firstname : "Jayne", lastname: "Cobb"}
];

persons.map(getFullName);

function getFullName(item) {
  return [item.firstname,item.lastname].join(" ");
}

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories