Transform arrays with map and filter
Turn data into useful values
React interfaces often start with data: product names, unread messages or tasks. JavaScript arrays hold ordered collections of values. An object groups named properties, and a function accepts inputs and returns a result. Use map() to compute a result for each item, and filter() to keep only items that satisfy a condition. These are JavaScript methods, not React APIs.
const names = ["Tea", "Rice"];const labels = names.map(name => "Item: " + name);console.log(JSON.stringify(labels));The output is ["Item: Tea","Item: Rice"]. const declares a binding that cannot be reassigned. The arrow function name => "Item: " + name is a callback: map calls it with each element and collects the returned values. An equivalent ordinary function is function label(name) { return "Item: " + name; }. The original array is unchanged because this callback does not mutate it.
Select visible items
An expression produces a value, such as item.stock > 0. A statement such as if (...) { ... } controls what happens. A callback can return a Boolean condition. filter keeps elements when the callback returns a truthy value and preserves their relative order. Values such as 0, false, an empty string, null and undefined are falsy; nonempty strings including "false" are truthy. Prefer explicit comparisons when they express the intended rule.
const items = [{name: "Tea", stock: 3}, {name: "Rice", stock: 0}, {name: "Salt", stock: 2}];const available = items.filter(item => item.stock > 0).map(item => item.name);console.log(JSON.stringify(available));The output is ["Tea","Salt"]. The dot accesses an object property. Filtering removes Rice, then mapping produces names rather than objects. A React list could later use those values to describe visible rows; JSX and keys are taught in Chapters 4 and 8. No browser or React package is required for this data example.
Avoid forgetting return
An arrow callback with braces has a statement body, so it needs an explicit return when you want to produce a value. Without it the callback returns undefined. Both methods create new arrays, but their callbacks can still mutate existing objects; neither automatically deep-copies the input.
const quantities = [2, 4];const bad = quantities.map(n => { n * 2; });const good = quantities.map(n => { return n * 2; });console.log(bad[0] === undefined);console.log(JSON.stringify(good));The first line is true because the deliberately incorrect callback returned nothing; the second is [4,8]. An empty array maps or filters to an empty array. Use === for strict equality: 0 === "0" is false. Use the practice task to combine filtering and mapping on a new dataset.