Iain Freestone

❓ JavaScript Q & A No. 2 - How do I receive the index of each element of an array along with the value when iterating over a list?

May 30, 2020

Use case

Take an array of numbers and return an array of objects containing the index and the value

Answser

const myArray = ["A", "B", "C", "D", "E"];

// Plain JavaScript
myArray.map((item, index) => ({ index: index, value: item }));

// Ramda
const mapIndexed = R.addIndex(R.map);
mapIndexed((item, index) => ({ index: index, value: item }), myArray)

// Lodash
_.map(myArray, (item, index) => ({ index: index, value: item }));

// Result
// [
//     { index: 0, value: 'A' },
//     { index: 1, value: 'B' },
//     { index: 2, value: 'C' },
//     { index: 3, value: 'D' },
//     { index: 4, value: 'E' }
// ]

Reference

Methods used

JavaScript - Array.prototype.map

Ramda - addIndex

Ramda - map

Lodash - map