Review the Map() function of JS through 6 simple examples

Posted by bobcooper on Mon, 03 Jan 2022 10:50:44 +0100

English| https://betterprogramming.pub/6-use-cases-for-map-in-javascript-a09f51ea2d2c

Yang Xiaoai

The map() function creates a new array by calling the callback function provided by the user. This function accesses each element in the call array. You can think of the map() method as going through a loop and writing a statement in the callback function to construct a new array.

What are the parameters?

The parameter is the callback function and the value used as "this" when the callback function is executed.

Callback function

callBackFunction: this function is called for each element in the array. After the callback function is executed, the return value is added to the new array to be constructed using map().

currentValue: it is the current element of the array, and the callback function traverses it.

Index: the index of the current element being processed by the callback function.

Array: is the array passed by the callback function.

This

thisArgument - this is the value used as this when callBackFunction is executed.

1. Double array elements

You can use the map() method to create a new array from another array. For example, you can double the elements of an integer array and construct a new array from the initial array.

let initialArray = [1,2,3,4,5]

let doubles = initialArray.map( function(num) {
  return num*2
})

console.log(initialArray); // returns [1,2,3,4,5]
console.log(doubles); // returns [2,4,6,8,10]

You can also use the arrow function to do the same.

let initialArray = [1,2,3,4,5]
let doubles = initialArray.map(x => x * 2);
console.log(initialArray); // returns [1,2,3,4,5]
console.log(doubles); // returns [2,4,6,8,10]

2. Reformat the objects in the array

You can reformat the object array using the map() method. For example, you have an array of objects that contain people's names and last names. In addition, you want to create a new array containing the full names of people in the people array.

var lineup = [
  {
    id: 1,
    firstName: "Magic",
    lastName: "Johnson"
  }, {
    id: 2,
    firstName: "Kobe",
    lastName: "Bryant"
  }, {
    id: 3,
    firstName: "Lebron",
    lastName: "James"
  }, {
    id: 4,
    firstName: "Kareem",
    lastName: "Abdul-Jabbar"
  }, {
    id: 5,
    firstName: "Shaquille",
    lastName: "O'Neal"
  }
];

Now you can create a new array containing reformatted objects.

let lineupSpeech = lineup.map( player => {
 let newObj = {};
 newObj["fullName"] = player.firstName + " " + player.lastName;
 return newObj;
 })

console.log(lineup);
/*
[
  { id: 1, firstName: 'Magic', lastName: 'Johnson' },
  { id: 2, firstName: 'Kobe', lastName: 'Bryant' },
  { id: 3, firstName: 'Lebron', lastName: 'James' },
  { id: 4, firstName: 'Kareem', lastName: 'Abdul-Jabbar' },
  { id: 5, firstName: 'Shaquille', lastName: 'O'Neal' }
]
*/
console.log(lineupSpeech);
/*
[
  { fullName: 'Magic Johnson' },
  { fullName: 'Kobe Bryant' },
  { fullName: 'Lebron James' },
  { fullName: 'Kareem Abdul-Jabbar' },
  { fullName: 'Shaquille O'Neal' }
]
*/

3. Callback some elements in the array

Instead of doubling every element in the array, you can double the specified element. For example, if the elements are odd, you might want to double them.

const numArray = [1, 2, 3, 4];
const sqrts = numArray.map( (num) => {
  return num % 2 === 1 ? Math.sqrt(num): num
 } );

4. Convert string to array

You can use the map() method to convert strings to arrays. You can do this from call() method for help.

const language = "JavaScript"
const map = Array.prototype.map
const letters = map.call(language, eachLetter => {
    return `${eachLetter}`
})

console.log(letters) //  ['J','a','v','a','S','c','r','i','p','t']

5. Traverse a NodeList

You can use the map() method to traverse the objects collected by queryselectorall (). This is possible because querySelectorAll() returns a NodeList.

let NodeList = document.querySelectorAll("p");

let values = Array.prototype.map.call(NodeList, function(obj) {
  return obj.value
})

6. In react Render a list in JS

You can also use map() when using the React library. You can render a list in React.

import React from 'react';
import ReactDOM from 'react-dom';

const numbers = [1,2,3,4,5];
const listItems = numbers.map( (number) =>
<li> {number} </li>
);

ReactDOM.render(
 <ul>{listItems}</ul>,
 document.getElementById('root')
);

summary

Built in functions in JavaScript are useful. You can use it to construct more complex functions. Therefore, understanding these functions is very important to improve your understanding of the programming language.

map() is also a useful built-in javascript method. You can create a new array from another array without using a while or for loop.

To sum up, the use cases of the map() method in this paper are as follows:

  • Doubles the elements of the array
  • Reformat the objects in the array
  • Apply callbacks to some elements in the array
  • Convert string to array
  • Traverse NodeList
  • Render the list in the React library

Finally, I hope today's content will help you. If you think today's content is useful, please remember to share it with your friends, which may help him.

Thank you for reading and have a nice programming!