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.