07 - Map Method

Transforming Arrays with map()

The map() method allows you to transform an array by applying a callback function to each element. This method returns a new array where each element has been transformed based on the function provided, without modifying the original array.

let result = arr.map(function(item, index, array) {
    // returns the transformed value instead of item
});

map() expects a callback as an argument, which means passing a function as a argument.

  • item: The current element being processed.
  • index: The index of the current element.
  • array: The array map() was called on.

Example 1: Add 1 to each number in an array

The map() method is commonly used when you need to transform an array by applying a function to each element. For instance, if we want to add 1 to each element of an array:

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

function addOne(num) {
    return num + 1;
}

const mappedArr = arr.map(addOne);

console.log(mappedArr);  // [2, 3, 4, 5, 6]

Alternatively, you can use an inline arrow function:

const mappedArr = arr.map(num => num + 1);

This creates a new array where each value has been incremented by 1, while the original array remains unchanged.


Example 2: Map to lengths of strings

You can also use map() to derive new data from an existing array. For example, if you want an array of string lengths:

let names = ["Bilbo", "Gandalf", "Nazgul"];
let lengths = names.map(item => item.length);

console.log(lengths);  // [5, 7, 6]

Here, map() iterates over the names array and returns the length of each string.


Example 3: Transforming Strings to Uppercase

The map() function can also be used to modify strings. For example, converting all the cat names to uppercase:

const cats = ["Leopard", "Jaguar", "Tiger", "Lion"];

function toUpper(string) {
    return string.toUpperCase();
}

const upperCats = cats.map(toUpper);

console.log(upperCats);  // ["LEOPARD", "JAGUAR", "TIGER", "LION"]

In this case, the toUpper() function is applied to each string in the cats array, returning a new array where all strings are capitalized.


Example 4: Map to Names

You can use map() to extract specific properties from objects in an array. For example, if you have an array of user objects and want to get an array of just the names:

let john = { name: "John", age: 25};
let pete = { name: "Pete", age: 30};
let mary = { name: "Mary", age: 28};

let users = [john, pete, mary];

let names = users.map(user => user.name);

console.log(names);  // ["John", "Pete", "Mary"]

Example 5: Map to Objects with New Properties

If you need to transform an array of objects into a new array with different properties, map() is useful. For example, you can combine a user’s name and surname into a fullName:

let john = { name: "John", surname: "Smith", id: 1};
let pete = { name: "Pete", surname: "Hunt", id: 2};
let mary = { name: "Mary", surname: "Key", id: 3};

let users = [john, pete, mary];

let usersMapped = users.map(user => ({
    fullName: `${user.name} ${user.surname}`,
    id: user.id
}));

console.log(usersMapped);
// [
//   { fullName: "John Smith", id: 1 },
//   { fullName: "Pete Hunt", id: 2 },
//   { fullName: "Mary Key", id: 3 }
// ]

there are two arrow functions: without body value => expr and with body value => {...}. Here JavaScript would treat { as the start of function body, not the start of the object. The workaround is to wrap them in the “normal” brackets.

let usersMapped = users.map(user => ({
	fullName: `${user.name} ${user.surname}`, id: user.id
}));

Example 6: Convert Kebab-case to camelCase

You can also use map() to apply transformations to strings, such as converting from kebab-case to camelCase:

function camelCase(str) {
    return str.split('-')
        .map((word, index) => index === 0 ? word : word[0].toUpperCase() + word.slice(1))
        .join('');
}

console.log(camelCase("background-color"));  // "backgroundColor"
console.log(camelCase("list-style-type"));   // "listStyleType"
  • split('-'): Splits the string into an array of words based on the - delimiter.
  • map(): Capitalizes the first letter of each word (except the first one), while keeping the rest of the word in lowercase.
  • join(''): Joins the words back together to form a single string in camelCase.

Key Points

  • map() creates a new array and does not modify the original array.
  • It transforms each element in the array according to the function passed to it.
  • It is ideal for tasks like transforming values, extracting properties from objects, or creating new object structures.
  • Unlike forEach(), map() always returns a new array, which can be assigned to a variable or used further in code.