BRUCE_FEBRUCE_FE

EN/CH Mode

BRUCE_FE JS Interview Notes - Implement Array Map Method

Learn how to manually implement JavaScript's Array.map() method, master higher-order functions and iterator patterns, and enhance frontend interview competitiveness.

影片縮圖

Lazy to read articles? Then watch videos!

Array.map() Method Overview

Array.map() is a commonly used array method in JavaScript that can transform each element in an array through a function and return a completely new array. This one-to-one transformation pattern makes data processing concise and elegant.

Native Map Method Usage

// Basic syntax
array.map(callback(currentValue[, index[, array]])[, thisArg])

// Usage example
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

Parameter Description

  • 1. callback: Function executed for each element, receives 1-3 parameters
  • 2. currentValue: The element currently being processed
  • 3. index (optional): Index of the current element
  • 4. array (optional): The array that called map
  • 5. thisArg (optional): Value to use as this when executing callback

Implement Array.map() Method

In interviews, implementing Array.map() is a good topic to test understanding of higher-order functions and JavaScript object-oriented programming. Here are the basic implementation steps:

Basic Implementation

// Basic map method implementation
Array.prototype.myMap = function(callback) {
  // Check if callback is a function
  if (typeof callback !== 'function') {
    throw new TypeError(callback + ' is not a function');
  }
  
  const result = [];
  const length = this.length;
  
  // Iterate through array
  for (let i = 0; i < length; i++) {
    // Only process existing elements (handle sparse arrays)
    if (i in this) {
      // Call callback function and store result in new array
      result[i] = callback(this[i], i, this);
    }
  }
  
  return result;
};

// Usage example
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.myMap(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

Practical Application Examples

Below are some practical application scenarios for the map method:

1. Format Data

// Raw user data from API
const users = [
  { id: 1, first_name: 'John', last_name: 'Doe', age: 28 },
  { id: 2, first_name: 'Jane', last_name: 'Smith', age: 32 },
  { id: 3, first_name: 'Bob', last_name: 'Johnson', age: 45 }
];

// Format data for UI display
const formattedUsers = users.myMap(user => ({
  id: user.id,
  fullName: `${user.first_name} ${user.last_name}`,
  ageGroup: user.age < 30 ? 'young' : 'adult'
}));

console.log(formattedUsers);
/*
[
  { id: 1, fullName: 'John Doe', ageGroup: 'young' },
  { id: 2, fullName: 'Jane Smith', ageGroup: 'adult' },
  { id: 3, fullName: 'Bob Johnson', ageGroup: 'adult' }
]
*/

2. Create DOM Element Arrays

// Example in React component
function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>
          <input type="checkbox" checked={todo.completed} />
          <span>{todo.text}</span>
        </li>
      ))}
    </ul>
  );
}

3. Mathematical Calculations and Array Transformations

// Calculate areas corresponding to radius array
const radii = [2, 5, 7.5, 10];
const areas = radii.myMap(radius => Math.PI * radius * radius);
console.log(areas);
// [12.57, 78.54, 176.71, 314.16] (rounded values)

// Convert Celsius temperatures to Fahrenheit
const celsius = [0, 15, 25, 30, 100];
const fahrenheit = celsius.myMap(temp => (temp * 9/5) + 32);
console.log(fahrenheit);
// [32, 59, 77, 86, 212]

Map vs Other Array Methods Comparison

The map method has some differences and overlaps in functionality with other array methods:

MethodFunctionReturn ValueExample
mapTransform each elementNew array, same lengtharr.map(x => x * 2)
filterFilter elements that meet conditionsNew array, length may decreasearr.filter(x => x > 5)
forEachExecute side effectsundefinedarr.forEach(console.log)
reduceReduce array to single valueAccumulated resultarr.reduce((a, b) => a + b)