How can I access iteration index in Ramda.map

。_饼干妹妹 提交于 2019-12-12 08:17:48

问题


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?


回答1:


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']



回答2:


You can also use mapIndexed from Ramda Adjunct which uses R.addIndex under the hood.

R.map function that more closely resembles Array.prototype.map. It takes two new parameters to its callback function: the current index, and the entire list.

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

It also offsers a reduceIndexed

const initialList = ['f', 'o', 'o', 'b', 'a', 'r'];

reduceIndexed((acc, val, idx, list) => acc + '-' + val + idx, '', initialList);
//=> "-f0-o1-o2-b3-a4-r5"



回答3:


As an alternative to addIndex you could use toPairs before mapping, from the documentation:

Converts an object into an array of key, value arrays. Only the object's own properties are used. Note that the order of the output array is not guaranteed to be consistent across different JS platforms.

The documentation talks only about objects but it works equally well with arrays. In your example:

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

// or, equivalent:

R.compose(
    R.map(([index, item]) => {}),
    R.toPairs,
)(items)

Bear in mind that in each index/value pair the index is always the first element, so the order is reversed compared to lodash (or the native Array.prototype.map).



来源:https://stackoverflow.com/questions/36573832/how-can-i-access-iteration-index-in-ramda-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!