Learn and Understand 4 Uses of JavaScript's Array.map()

Learn and Understand 4 Uses of JavaScript's Array.map()

In this JavaScript Array tutorial, we'll look at 4 noteworthy uses of the .map() in JavaScript. Array.map() is a very powerful method in JavaScript. Here's 4 common uses.

From the classic forloop to the forEach() method, various techniques and methods used to iterate through datasets abound JavaScript. However, one of the more popular methods is the .map() method.

.map() creates an array from calling a specific function on each item in the parent array. .map() is a non-mutating method in that it creates a new array as against mutating methods which only make changes to the calling array. This can be tricky to remember.

In this post, we'll look at 4 noteworthy uses of the .map() in JavaScript. Let's begin!

Table of Contents

  • Calling a Function on Each Item in an Array
  • Converting a String to an Array
  • Rendering Lists in JavaScript Libraries
  • Reformatting Array Objects

Calling a Function on Each Item in an Array

.map() as earlier stated accepts a callback function as one of its arguments and an important parameter of that function is the current value of the item being processed by the function. This is a required parameter. With this parameter, we can modify each individual item in an array and create a new function off it. Here's an example:

const sweetArray = [2, 3, 4, 5, 35]
const sweeterArray = sweetArray.map(sweetItem => {
    return sweetItem * 2
})

console.log(sweeterArray) // [4, 6, 8, 10, 70]

This can even be simplified further to make it cleaner with:

// create a function to use
const makeSweeter = sweetItem => sweetItem * 2;

// we have an array
const sweetArray = [2, 3, 4, 5, 35];

// call the function we made. more readable
const sweeterArray = sweetArray.map(makeSweeter);

console.log(sweeterArray); // [4, 6, 8, 10, 70]

Having code like sweetArray.map(makeSweeter) makes that a bit more readable when you jump into this code.

Converting a String to an Array

.map() is known to belong to the Array prototype. How about we use it to convert a String to an Array. Not to worry, we are not developing the method again to work for strings rather we will use the special .call() method.

Everything in JavaScript is an object and methods are just functions attached to these objects. .call() allows us to utilize the context of one object on another. Therefore, we would be copying the context of .map() in an array over to a string.

.call() can be passed arguments of, the context to be used, and "parameters for the arguments of the original function". Sounds like gibberish? Here's an example.

const name = "Chuloo"
const map = Array.prototype.map

const newName = map.call(name, eachLetter => {
    return `${eachLetter}a`
})

console.log(newName) // ["Ca", "ha", "ua", "la", "oa", "oa"]

Here, we simply used the context of .map() on a String and passed an argument of the function which .map() expects. Voila! We have a wolf-lang looking characters in our console. Yikes!

This functions like the .split() method of a String only that each individual string characters can be modified before being returned in an array.

Rendering Lists in JavaScript Libraries

JavaScript libraries like React utilize .map() to render items in a list. This requires JSX syntax however as .map() method is wrapped in mustache-like JSX syntax. Here's a good example of a React component.

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

const names = ["john", "sean", "mike", "jean", "chris"];

const NamesList = () => (
  <div>
    <ul>{names.map(name => <li key={name}> {name} </li>)}</ul>
  </div>
);

const rootElement = document.getElementById("root");
ReactDOM.render(<NamesList />, rootElement);

Are you unfamiliar with React? This is a simple stateless component in React which renders a div with a list. The individual list items are rendered using .map() to iterate over the names array initially created. This component is rendered using ReactDOM on the DOM element with id of root.

Reformatting Array Objects

How about handling objects in an array? .map() can be used to iterate through objects in an array and in a similar fashion to traditional arrays, *_modify the content of each individual object *_and return a new array. This modification is done based on what is returned in the callback function. Here's an example:

const myUsers = [
    { name: 'chuloo', likes: 'grilled chicken' },
    { name: 'chris', likes: 'cold beer' },
    { name: 'sam', likes: 'fish biscuits' }
]

const usersByFood = myUsers.map(item => {
    const container = {};

    container[item.name] = item.likes;
    container.age = item.name.length * 10;

    return container;
})

console.log(usersByFood);
// [{chuloo: "grilled chicken", age: 60}, {chris: "cold beer", age: 50}, {sam: "fish biscuits", age: 30}]

All we did is simply modify each object in the array using the bracket and dot notation. This use case can be employed to process or condense received data before being saved or parsed on a frontend application.

Conclusion

In this post, we looked at for main uses of the .map() method in JavaScript. A thing to note is that in combination with other methods, the functionality of .map() can be extended and utilized powerfully. Try to find out more use cases. Leave your comments, questions, and feedback in the comments section, they'll be appreciated!

JavaScript WebDev

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Create a Line Through Effect with JavaScript

In this post we are going to create an amazing line through effect, with help of CSS and lots of JavaScript. So, head over to your terminal and create a folder LineThroughEffect. Create three files -index.html, main.js and styles.css inside it.