JS Built-ins
← Array48 / 226
ArrayArray.prototype.entriesintermediate

Array.prototype.entries() β€” index/value pairs

πŸ“– Usage Example
const fruits = ['apple', 'banana', 'cherry']
for (const [i, v] of fruits.entries()) {
  console.log(i, v)  // 0 apple, 1 banana, 2 cherry
}

Use entries() with for-of destructuring to loop over both the index and value of each element.

Array.prototype.entries() β€” working with pairs

Iterating over entries() gives you both the index and the value at each step. This is helpful when you need both without maintaining a separate counter.

Challenge: Implement getIndexValuePairs(arr) that returns an array of [index, value] pairs from ['a', 'b', 'c'].

getIndexValuePairs(['a', 'b', 'c']) // β†’ [[0, 'a'], [1, 'b'], [2, 'c']]
πŸ’‘ Hints (2)
  • β€’ `for (const [i, v] of arr.entries())` destructures each pair cleanly.
  • β€’ You can also use `Array.from(arr.entries())` for a one-liner.