자바스크립트 배열 매핑(Mapping)

In JavaScript, mapping refers to the process of transforming each element of an array into a new array based on a specific condition or operation. The result is a new array with the same length as the original array, but with modified or transformed elements. This is extremely useful when you want to manipulate array data without modifying the original array itself.

The map() Method

The map() method is a built-in function in JavaScript that allows you to apply a specified function to each element of an array and returns a new array with the results. It takes in a callback function as an argument, which is executed for each element in the array.

Here’s the syntax for using the map() method:

const newArray = array.map(callbackFunction);

Let’s see some examples to understand how to use the map() method:

Example 1: Doubling the elements of an array

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

const doubledNumbers = numbers.map((num) => num * 2);

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

In this example, we have an array of numbers. We use the map() method to double each number in the array by using an arrow function num => num * 2. The resulting array doubledNumbers contains the doubled values of the original array.

Example 2: Converting string to uppercase

const fruits = ['apple', 'banana', 'orange'];

const uppercaseFruits = fruits.map((fruit) => fruit.toUpperCase());

console.log(uppercaseFruits);
// Output: ['APPLE', 'BANANA', 'ORANGE']

In this example, we have an array of fruits in lowercase. We use the map() method with the arrow function fruit => fruit.toUpperCase() to convert each fruit string to uppercase. The resulting array uppercaseFruits contains the uppercase versions of the original array elements.

Example 3: Extracting specific properties from an array of objects

const users = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'David' }
];

const userIds = users.map((user) => user.id);

console.log(userIds);
// Output: [1, 2, 3]

In this example, we have an array of user objects with properties like id and name. We use the map() method to extract only the id property from each object and store them in a new array userIds.

Conclusion

The map() method in JavaScript is a powerful tool for manipulating array data. It allows you to easily transform each element of an array based on a specified function or condition. With the map() method, you can create new arrays with modified or extracted elements without changing the original array. This feature is particularly useful when working with large datasets or when you need to perform data transformations in JavaScript.