DEV Community

german9304
german9304

Posted on • Edited on

javascript: arrays map function

Welcome to an introduction to the map function in an array.

The map in an array is a function that takes your elements and transforms them into new elements. One of the benefits of map is that it does not mutate your original elements it creates a new array.

mutation: it means when your original array gets modified,
for instance: the use of the push function in an array mutates your original element, the original array gets modified.

Let's dive in:

What do I mean by transforms your elements?

  • Let's say we have an array of numbers:
const numbers = [1, 2, 3, 4, 5, 6];
  • And We would like to create an array of those elements with every element multiplied by 2, in order words: an array with their double number. Well map would do this very simple:
const numbers = [1, 2, 3, 4, 5, 6];
let doubleNumbers = numbers.map((number) => number * 2); // with arrow function 

console.log(doubleNumbers) // [ 2, 4, 6, 8, 10, 12 ]

// numbers remains intact, it is not mutated

console.log(numbers) // [ 1, 2, 3, 4, 5, 6 ]

Pretty simple right? But, how does map work internally?

This is a small representation of map, of course the original has more things to check or code, I just wanted to provide an example of this.

/**
 * map function
 * @param {Array} elements elements to transform
 * @param {function} cb callback that will transform the elements
 */
function map(elements, cb) {
  let newElements = [];
  for (let i = 0; i < elements.length; i++) {
    newElements.push(cb(elements[i]));
  }

  return newElements;
}

let resultDouble = map(numbers, number => number * 2); 
console.log(resultDouble); // [ 2, 4, 6, 8, 10, 12 ]

Note:
I've been using arrow function, but you can use normal function as well.

let myFunc = number => number * 2;

let myFunc2 = function(number) {
  return number * 2;
}

Pretty great right? you the the full benefits of immutability and also you accomplish to get a new transformed array.

What else could I do with map? well:

Let's give more examples:

  • Suppose you would like to return a string representation of an array of objects we can use map!

const person = [
  {
    name: 'john',
    lastName: 'frank',
    age: 34
  },
  {
    name: 'Mark',
    lastName: 'Roger',
    age: 40
  }
];

const personInfo = person.map(person => {
  return `My name is ${person.name}, Last Name is ${person.lastName} and age ${person.age}`;
});

console.log(personInfo); 
// Result: 
// [ 'My name is john, Last Name is frank and age 34',
 // 'My name is Mark, Last Name is Roger and age 40' ]
  • What about html?

const people = [
  {
    name: 'john',
    lastName: 'frank',
    age: 34
  },
  {
    name: 'Mark',
    lastName: 'Roger',
    age: 40
  }
];


const peopleHtml = people.map(person => {
  return `
      <li> 
        <p> name: ${person.name} </p>
        <p> last name: ${person.lastName} </p>
        <p> age: ${person.age} </p>
      </li>
    `;
});

const container = document.querySelector('div');

container.innerHTML = peopleHtml.join('');

console.log(peopleHtml.join(''))

/*

<li>
<p> name: john </p>
<p> last name: frank </p>
<p> age: 34 </p>
</li>

<li>
<p> name: Mark </p>
<p> last name: Roger </p>
<p> age: 40 </p>
</li>

*/
  • In react we often use the map function to create jsx:

function App() {

  const numbers = [1, 2, 3, 4, 5];

  return (
    <div className="App">
      <h1> map </h1>
      <ul>
        {numbers.map((number) => (
          <li> {number} </li>
        ))}
      </ul>
    </div>
  )
}

There are more cases to cover, however I wanted to make it simple so you get a better understand what the map function in an array is and why it is helpful.

If I forgot things or any feedback please leave a comment.

Thank you for taking the time to read it! Happy coding :)

Top comments (0)