Array.map() Method
Tags: webdev, javascript, beginners, programming
Published: 2023-06-15 09:10:24

## What is Map Function?

In JavaScript, the `map()` method is a function that creates a new array with the results of calling a provided function on every element in the calling array.

## Syntax

Here's the syntax for using `map()`:

```js
const newArray = array.map(function (element, index, array) {
	// return element for newArray
});
```

The `map()` function takes a callback function as an argument, which is applied to each element of the array. The callback function takes three arguments:

1. `element`: the current element being processed in the array
2. `index` (optional): the index of the current element
3. `array` (optional): the array that map() is being applied to

The `map()` function returns a new array with the same `length` as the original array, but with each element transformed by the callback function.

Here's an example of using `map()` to double the value of each element in an array:

```js
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function (number) {
	return number * 2;
});

console.log(doubledNumbers); // prints [2, 4, 6, 8, 10]
```

In the example above, the `callback` function is an anonymous function that takes a single argument, `number`, and returns its value multiplied by 2. The `map()` method calls this function for each element in the `numbers` array and creates a new array with the returned values.

You can also use an arrow function as the `callback` function, like this:

```js
const doubledNumbers = numbers.map((number) => number * 2);
```

The `map()` method is useful for transforming an array into a new array of a different shape or structure. It is similar to the `forEach()` method, but it returns a new array, whereas `forEach()` does not return a new array.

## Examples

Here are a few more examples of how you can use `map()`:

### Example 1: Transforming an array of strings to Uppercase

```js
const names = ["Alice", "Bob", "Charlie"];

const upperCaseNames = names.map((name) => name.toUpperCase());

console.log(upperCaseNames); 
// prints ['ALICE', 'BOB', 'CHARLIE']
```

### Example 2: Transforming an array of numbers to its square

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

const squareNumbers = numbers.map((number) => number * number);

console.log(squareNumbers); 
// prints [1, 4, 9, 16, 25]
```

### Example 3: Extracting the values of an object

```js
const users = [
	{ id: 1, name: "Alice" },
	{ id: 2, name: "Bob" },
	{ id: 3, name: "Charlie" },
];

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

console.log(names); 
// prints ['Alice', 'Bob', 'Charlie']
```

### Example 4: Transforming an array of objects

```js
const users = [
	{ id: 1, firstName: "Alice", lastName: "Wonderland" },
	{ id: 2, firstName: "Bob", lastName: "Marley" },
	{ id: 3, firstName: "Charlie", lastName: "Brown" },
];

const newUsers = users.map((user) => ({
	id: user.id,
	fullName: user.name + " " + user.lastName,
}));

console.log(newUsers);

// prints [{ id: 1, fullName: 'Alice Wonderland' }, { id: 2, fullName: 'Bob Marley' }, { id: 3, fullName: 'Charlie Brown' }]
```

Note: We can also use Object Destructuring to make the code more readable. Here's how:

```js
const newUsers = users.map(({ id, firstName, lastName }) => ({
	id,
	fullName: `${firstName} ${lastName}`,
}));
```

### Example 5: Transforming an array of objects

Here is an example of how you might use the `map()` method in the context of an e-commerce website.

Imagine that you have an array of products, and each product is represented by an object with the following properties:

1. `id`: the unique ID of the product
2. `name`: the name of the product
3. `price`: the price of the product

You can use the `map()` method to create a new array that contains the `names` and `prices` of all the products.

Here's the code that does this:

```js
const products = [
	{ id: 1, name: "Product 1", price: 10 },
	{ id: 2, name: "Product 2", price: 15 },
	{ id: 3, name: "Product 3", price: 20 },
];

const namesAndPrices = products.map((product) => {
	return {
		name: product.name,
		price: product.price,
	};
});

// or

const anotherWay = products.map(({ name, price }) => ({ name, price }));

console.log(namesAndPrices);

// prints [{ name: 'Product 1', price: 10 }, { name: 'Product 2', price: 15 }, { name: 'Product 3', price: 20 }]
```

## `map()` vs `forEach()`

The `map()` method is similar to the `forEach()` method, but there are a few key differences:

1. The `map()` method returns a new array, whereas `forEach()` does not return a new array.
2. The `map()` method can be used to transform an array into a new array of a different shape or structure, whereas `forEach()` can only be used to iterate over the elements of an array.
3. The `map()` method is chainable, whereas `forEach()` is not.

### Chainable Methods

A chainable method is a method that can be called on an object and returns the object itself. This allows us to chain multiple methods together.

For example, the `map()` method is chainable, so we can call it on an array and then call another method on the returned array. Here's an example:

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

const doubledNumbers = numbers
	.map((number) => number * 2)
	.filter((number) => number > 5);

console.log(doubledNumbers); // prints [6, 8, 10]
```

Note: We're going to learn more about `array.filter()` in coming doc. For now just remember it is used to filter the data from the array based on condition 

In the example above, we first call the `map()` method on the `numbers` array to create a new array with the doubled values. Then we call the `filter()` method on the returned array to create a new array with only the values that are greater than 5.

The `forEach()` method is not chainable, so we can't call another method on the returned value. Here's an example:

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

const doubledNumbers = numbers
	.forEach((number) => number * 2)
	.filter((number) => number > 5);
// This will error
// TypeError: numbers.forEach(...).filter is not a function
```

In the example above, we first call the `forEach()` method on the `numbers` array to create a new array with the doubled values. Then we try to call the `filter()` method on the returned array to create a new array with only the values that are greater than 5. But this will error because the `forEach()` method does not return a new array, so we can't call another method on the returned value.

## Conclusion

In this article, we learned about the `map()` method in JavaScript. We learned about the syntax for using `map()`, how to use it to transform an array, and how to use it to extract the values of an object.