How to Use Array Index in map() Instead of the Item Value
How to Use Array Index in map() Instead of the Item Value
I needed array indices for numbering items, but every tutorial shows using map() for values. I kept getting error after error trying to access positions.
The Problem
// What I was doing - getting only valuesconst names = ['John', 'Alice', 'Bob'];const result = names.map(name => name);// Result: ["John", "Alice", "Bob"] - not what I neededI needed indices like [0, 1, 2] but map() only gave me values. All the Stack Overflow answers said “use a for loop with i++” - which felt like giving up on functional programming.
The Solution: Callback Destructuring
You can access array indices in map() by using array destructuring in the callback function parameters.
const names = ['John', 'Alice', 'Bob'];const indices = names.map((_, i) => i);// Result: [0, 1, 2]How It Works
- First parameter (
_): The array item (ignored with underscore) - Second parameter (
i): The index (what we actually want) - Return
ito get the current index
The underscore _ signals intentional ignoring of the item parameter - this is a common JavaScript pattern.
Why This Matters
- Declarative vs Imperative: No need for manual counter variables
- Functional: Maintains pure function principles
- Clean: Less boilerplate code
- Readable: Clear intent - “give me indices”
Common Mistakes
I made these errors before finding the solution:
// WRONG: Trying to access index through other array methodsconst indices = names.filter((_, i) => i); // Returns [0, 1, 2] but confusing
// WRONG: Using manual counter when unnecessarylet counter = 0;const indices = names.map(() => counter++); // Works but not declarativePractical Examples
Adding Row Numbers
const users = ['John', 'Alice', 'Bob'];const numberedUsers = users.map((name, index) => `${index + 1}. ${name}`);// Result: ["1. John", "2. Alice", "3. Bob"]Creating Indexed Objects
const fruits = ['apple', 'banana', 'orange'];const indexedFruits = fruits.map((fruit, index) => ({ id: index, name: fruit, position: index + 1}));// Result: [// { id: 0, name: 'apple', position: 1 },// { id: 1, name: 'banana', position: 2 },// { id: 2, name: 'orange', position: 3 }// ]Generating Enumerated Arrays
const tasks = ['code', 'test', 'deploy'];const enumeratedTasks = tasks.map((task, index) => ({ task, enum: `[${index}]`}));// Result: [// { task: 'code', enum: '[0]' },// { task: 'test', enum: '[1]' },// { task: 'deploy', enum: '[2]' }// ]When to Use This Pattern
Perfect for:
- Enumeration tasks
- Position-based UI rendering
- Index reference arrays
- When you need both value and index in transformations
Not ideal for:
- Simple value transformations (use regular map)
- Filter operations (use filter with index)
- Complex state management
Performance Considerations
This approach is generally as performant as traditional loops. Modern JavaScript engines optimize these patterns well.
// Performance: Both approaches are similarconsole.time('map-index');const indices1 = Array(1000000).fill(0).map((_, i) => i);console.timeEnd('map-index');
console.time('for-loop');const indices2 = [];for (let i = 0; i < 1000000; i++) { indices2.push(i);}console.timeEnd('for-loop');Related Knowledge
The map() callback function actually receives three parameters:
- Current item
- Current index
- Original array
const arr = ['a', 'b', 'c'];arr.map((item, index, originalArray) => { console.log({ item, index, originalArray }); return index;});Final Words
Final Words + More Resources
My intention with this article was to help others share my knowledge and experience. If you want to contact me, you can contact by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!
Reference Links
- MDN Array.prototype.map()
- JavaScript Array Destructuring
- Reddit discussion that inspired this post
Conclusion
Use (_, i) => i in map() callbacks to get array indices instead of values. This functional approach eliminates manual loops while keeping your code clean and declarative. The next time you need indices, reach for this pattern instead of the old-school for loop.
Comments