Explain Codes LogoExplain Codes Logo

Index inside map() function

javascript
map-function
indexing
immutable-js
Anton ShumikhinbyAnton Shumikhin·Oct 17, 2024
TLDR

Access the index within map() by accepting it as the second argument in your callback:

const array = ['a', 'b', 'c']; const withIndex = array.map((element, index) => ({element, index})); console.log(withIndex); // [{ element: 'a', index: 0 }, { element: 'b', index: 1 }, { element: 'c', index: 2 }]

This line up of code is efficient and gives you the power of tracking element's position during mapping.

Index gymnastics with Immutable.js

When working with Immutable.js, you can equilibrate the same index canter over immutable List :

const { List } = require('immutable'); const myList = List(['x', 'y', 'z']); const indexedList = myList.map((item, index) => ({item, index})); console.log(indexedList.toArray()); // [{ item: 'x', index: 0 }, { item: 'y', index: 1 }, { item: 'z', index: 2 }]

See? That index rodeo is your secret weapon for keeping track of values without touching the original data.

Classic function for classic context

Arrow functions, they are sleek and cool but they don't have their this. Don't worry though, good ole regular functions have your back!

function myMapper(el, idx) { console.log(this.prefix + el, idx); // "this" is BACK, baby! } const boundMap = Array.prototype.map.bind(array, myMapper, {prefix: 'value:'}); boundMap(); // logs "value:a 0", "value:b 1", "value:c 2"

When the callback wants to have its own this, don't hesitate to explicitly bind it!

Become the map() whisperer

Double-tap – using the third parameter

The third argument of map() gives you a sneak peek of the whole array. Often unnoticed, it can hand you some useful context:

array.map((el, idx, arr) => { console.log(`Hey ${el}, don't feel lonely. You are part of `, arr); });

Enlist index for state tracking

Utilizing the index can be your guardian for tracking changes to arrays when dealing with React state arrays:

stateArray.map((item, index) => { // Guard's log – day #${index}: I witnessed ${item} changes today! });

Detour: Ramda's way of indexed mapping

Looking for other ways to wrangle those naughty indices? Ramda library throws in a addIndex challenge:

const R = require('ramda'); const indexedMap = R.addIndex(R.map); const result = indexedMap((elem, idx) => [elem, idx], ['a', 'b', 'c']); console.log(result); // [['a', 0], ['b', 1], ['c', 2]]

Delving deep with index

Conditionals powered by index

You can make the index run your conditional logic. It's like being the judge at a fashion show:

const highlightedIndices = array.map((el, idx) => idx % 2 === 0 ? `<strong>${el}</strong>` : el // "You. Yes, you. You're bold today. Deal with it." );

Transformed arrays: Now with more context!

Combine the index with array transformations for cloak and dagger operations:

const withPrevious = array.map((current, index, arr) => index === 0 ? current : [arr[index - 1], current] // "Harry, meet Sally. You two will be paired for this project." );

Debugging using map: comment style

Cast a spell of console logs within map:

array.map((el, idx) => { // "Elementary, my dear Watson!" Here's a clue for debugging! if (idx === 1) console.log(`Debug at index ${idx}`, el); return el.toUpperCase(); });