Map array

2 snippets across 2 stacks - JavaScript, React

JSJavaScript

map()

JS · Arrays
Syntax
arr.map(callback(element, index, array))
Example
const prices = [10, 25, 50];
const withTax = prices.map(p => +(p * 1.08).toFixed(2));
console.log(withTax);
Output
[10.8, 27, 54]

Note map() returns a new array of the same length. If you do not need the return value, use forEach() instead.

REReact

Lists & Keys

RE · Components
Syntax
{items.map(item => (
  <Component key={item.uniqueId} {...item} />
))}
Example
function TaskList({ tasks }) {
  return (
    <ul>
      {tasks.map(task => (
        <li key={task.id}>
          <span>{task.title}</span>
          {task.done && <span> (completed)</span>}
        </li>
      ))}
    </ul>
  );
}

Note Keys must be stable, unique among siblings, and derived from data (like a database ID). Never use array index as key if the list order can change -- it causes subtle rendering bugs and broken state.

Frequently asked questions

How does JavaScript handle map array?
This task is covered in 2 stacks on this page: JavaScript, React. The "map()" snippet in JavaScript uses `arr.map(callback(element, index, array))`.
Which code does the JavaScript example use?
The "map()" snippet uses `arr.map(callback(element, index, array))`, from the Arrays section of the JavaScript cheat sheet.
Which stacks cover "map array" on this page?
JavaScript, React. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "map()": map() returns a new array of the same length. If you do not need the return value, use forEach() instead.