Arrays and Data Transformation

JavaScript · 3 minute lesson

An array stores an ordered collection of values. It is useful for lesson titles, product records, search results, and many other lists. Each item has an index beginning at zero, while the length property reports how many items the array contains.

The map method builds a new array by calling a function for each existing item. The returned value from that function becomes the corresponding value in the result. This is helpful when you want to turn records into labels or prepare data for a user interface.

Map is for producing a transformed collection. If you only want to perform an action for each item, choose an iteration approach that communicates that purpose. Keeping transformations clear makes later code easier to review. It also helps avoid changing the original data when another part of the application still needs it.

Try the example

const lessons = [
  { title: "Variables", minutes: 5 },
  { title: "Functions", minutes: 8 }
];

const labels = lessons.map(lesson =>
  `${lesson.title}: ${lesson.minutes} min`
);
console.log(labels);

Practice

Make an array containing three lesson records. Use map to produce a new array of lesson titles. Print both arrays and check that the original records still contain their title and duration properties.

Continue learning: Official documentation.