How can I access iteration index in Ramda.map

Glen Swift picture Glen Swift · Apr 12, 2016 · Viewed 9.9k times · Source

I used to write something like

_.map(items, (item, index) => {});

with lodash. Usually I don't need index but sometimes it's useful.

I'm migrating to Ramda now:

R.map((item, index) => {}, items);

index is undefined. Sure, I can create variable index in upper scope and increment it every time in map body but it's kinda wrong from FP point of view that Ramda stands for. So is there's any build in way of getting iteration index?

Answer

andyk picture andyk · Apr 12, 2016

Check out addIndex:

Creates a new list iteration function from an existing one by adding two new parameters to its callback function: the current index, and the entire list.

This would turn, for instance, Ramda's simple map function into one that more closely resembles Array.prototype.map. Note that this will only work for functions in which the iteration callback function is the first parameter, and where the list is the last parameter. (This latter might be unimportant if the list parameter is not used.)

Example from the docs:

var mapIndexed = R.addIndex(R.map);
mapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']);
//=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r']