[JavaScript] Transforming Array Data and Generating New Arrays with the map Method

目次

Overview

When you need to extract specific pieces of information from a data list, such as pulling only IDs from an API response or creating a new list of product prices including tax, the map method is the ideal tool. This method executes a specified function for every element in an array and collects the results into a brand-new array. It is a fundamental technique for data transformation and extraction because it allows you to create a modified version of data without changing the original array.

Specifications (Input/Output)

map Method

This method transforms all elements in an array and returns a new array of the same size.

Argument/ReturnDescription
callbackFnThe function executed for each element: (element, index, array) => return_value
Return ValueA new array composed of the values returned by the callback function.
  • Input: The original array before transformation.
  • Output: A new array after transformation.
  • Feature: The number of elements (length) in the output array is always the same as the input array.

Basic Usage

1. Value Transformation

You can perform calculations or join strings for each element.

const ids = [1, 2, 3];

// Add a prefix to each ID
const userIds = ids.map((id) => `user_${id}`);

console.log(userIds); // ["user_1", "user_2", "user_3"]

2. Using the Index

The callback function can receive the index as the second argument.

const items = ['Project A', 'Project B', 'Project C'];

// Generate strings with sequence numbers
const numberedItems = items.map((item, index) => `${index + 1}: ${item}`);

console.log(numberedItems); // ["1: Project A", "2: Project B", "3: Project C"]

3. Extracting Properties from Objects

This is the most common pattern when handling API responses.

const staffMembers = [
    { id: 10, name: 'Mori' },
    { id: 20, name: 'Komori' }
];

// Create an array containing only the names
const nameList = staffMembers.map((staff) => staff.name);

console.log(nameList); // ["Mori", "Komori"]

Full Code (HTML / JavaScript)

This simulation takes a list of pre-tax prices, adds 10% consumption tax, and formats them into a currency-formatted list for display on a screen.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Price Calculator</title>
    <style>
        .price-panel {
            font-family: 'Segoe UI', Arial, sans-serif;
            max-width: 400px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background-color: #f9f9f9;
        }
        h3 { margin-top: 0; color: #333; }
        .price-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .price-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
        }
        .price-item:last-child { border-bottom: none; }
        .original-price { color: #888; font-size: 0.9em; }
        .tax-included { color: #d32f2f; font-weight: bold; }
    </style>
</head>
<body>

<div class="price-panel">
    <h3>Product Price List (Tax Included)</h3>
    <ul id="display-area" class="price-list">
        </ul>
</div>

<script src="calculator.js"></script>
</body>
</html>

JavaScript

/**
 * Price Calculation Script
 * Converting data structures using the map method
 */

// 1. Original Data (Array of pre-tax prices)
const basePrices = [1000, 2500, 500, 12800, 980];

const displayArea = document.getElementById('display-area');

/**
 * Helper function to format numbers as currency
 * @param {number} num 
 * @returns {string} e.g., "1,000"
 */
const formatCurrency = (num) => {
    return num.toLocaleString();
};

/**
 * Data transformation and rendering process
 */
const renderProductPrices = () => {
    // 2. Data transformation with map
    // Convert numeric array -> Array of objects containing formatted HTML strings
    const transformedPrices = basePrices.map((price) => {
        const taxRate = 0.1;
        const total = Math.floor(price * (1 + taxRate)); // Calculate tax
        
        return {
            original: formatCurrency(price),
            final: formatCurrency(total)
        };
    });

    // 3. Output to the screen
    transformedPrices.forEach((item) => {
        const li = document.createElement('li');
        li.className = 'price-item';
        li.innerHTML = `
            <span class="original-price">Pre-tax: ¥${item.original}</span>
            <span class="tax-included">Tax-in: ¥${item.final}</span>
        `;
        displayArea.appendChild(li);
    });
};

renderProductPrices();

Custom Points

If you want to return an object directly using an arrow function, you must wrap the object in parentheses, such as map(val => ({ id: val })). You can also implement conditional logic within the transformation using ternary operators, allowing you to change the result based on the value, such as converting test scores into “Pass” or “Fail” labels.

Important Notes

The map method always returns a new array as its result. If you simply want to iterate through an array without creating a transformed version of the data, you should use forEach instead to avoid unnecessary memory usage. Furthermore, the length of the array will never change; if the input has ten elements, the output will also have ten. If you need to both filter and transform data, you should combine map with the filter method. When using async/await inside a map callback, it returns an array of Promises, which requires Promise.all to resolve the values.

Advanced Usage

Method Chaining with filter

In professional development, it is common to chain filtering and transformation together in a single flow.

const inventory = [
    { name: 'Server', price: 100000 },
    { name: 'Mouse', price: 3000 },
    { name: 'Keyboard', price: 15000 }
];

// 1. Extract items priced at 10,000 or more (filter)
// 2. Create an array of only those item names (map)
const highValueItems = inventory
    .filter(item => item.price >= 10000)
    .map(item => item.name);

console.log(highValueItems); // ["Server", "Keyboard"]

Summary

The map method serves as one of the most powerful tools for data transformation in JavaScript. When you need a one-to-one mapping between input and output, such as converting numbers to strings or objects to specific property values, you should choose map. It provides a safe way to generate new datasets for your application without contaminating the original data sources.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次