To find an index of the current iterable inside the map() function in JavaScript, you can use the callback function’s second parameter, which is an index.
The index used inside the map() method indicates the position of each item in an array, but it does not modify the original array.
Syntax
array.map(function(currentItem, index, arrayobj)
{
});
Parameters
- currentItem(required): The current element being processed in the array.
- index(optional): The index of the current element being processed in the array.
- arrayobj(optional): The array object where the current item belongs.
Return Value
Returns a new array
Visual Representation Example 1: How to Use Index inside map() Function
let arr = [5, 10, 15, 20, 25];
let doubledNumbers = arr.map((currentValue, index) => {
console.log(`Index: ${index}, Value: ${currentValue}`);
return currentValue * 2;
});
console.log(doubledNumbers);
console.log("Original Array: "+ arr);
Output
Index: 0, Value: 5
Index: 1, Value: 10
Index: 2, Value: 15
Index: 3, Value: 20
Index: 4, Value: 25
[ 10, 20, 30, 40, 50 ]
Original Array: 5,10,15,20,25
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
great guide but Map and map are different things in some places map is written as Map as it has different functions and does different things
Great examples! Just tried this myself and it works perfectly.
Really useful tutorial! You’ve got a great blog for anyone wishing to learn a variety of programming!