JS Built-ins
← Array98 / 226
ArrayArray.prototype.forEachbeginner

Array.prototype.forEach() β€” collect property values

πŸ“– Usage Example
const result = {}
['a', 'b', 'c'].forEach((v, i) => { result[i] = v })
// result β†’ {0:'a', 1:'b', 2:'c'}

Use forEach() to build an object or other data structure by iterating over array elements.

Array.prototype.forEach() β€” collecting values

forEach can be used to collect property values from an array of objects into a new array.

Challenge: Implement collectStrings(items) that uses forEach to collect all label values into a string array.

collectStrings([{label:'a'},{label:'b'}]) // β†’ ['a', 'b']
collectStrings([])                         // β†’ []
πŸ’‘ Hints (2)
  • β€’ Declare an empty array before `forEach`, then `push` inside the callback.
  • β€’ This pattern is equivalent to `items.map(item => item.label)`.