首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ramda.js对嵌套列表进行索引

使用ramda.js对嵌套列表进行索引
EN

Stack Overflow用户
提问于 2017-09-29 16:44:55
回答 1查看 73关注 0票数 0

我正在学习函数式编程,如果有任何帮助我将不胜感激。使用ramda.js时,以下代码的功能等价物是什么?

代码语言:javascript
复制
const indexArray = (array)=>{
   let idx = 0;
   return array.map((l)=>{
      return l.map((w)=>{
         let nw = { id: idx, val: w }
         idx++
         return nw
      })
   })
}

indexArray([["Hello", "World"],["Foo", "Bar"]]) 

//=> [[{"id":0,"val":"Hello"},{"id":1,"val":"World"}],[{"id":2,"val":"Foo"},{"id":3,"val":"Bar"}]] 
EN

回答 1

Stack Overflow用户

发布于 2017-09-30 13:19:05

使用Scott的部分回答(谢谢!)和一个递归函数,我想出了下面的解决方案。然而,我不禁想,一定有更优雅的方式来做这件事。

代码语言:javascript
复制
const indexElements = R.pipe(R.flatten, R.addIndex(map)((val, idx) => ({idx, val})))

const lengths = R.map((l)=>l.length)

const rf = (output, input, indexes)=>{ 
  if (indexes.length == 0) return output
  let index = indexes[0]
  return rf(
    R.append(R.take(index,input), output),
    R.drop(index, input),
    R.drop(1, indexes)
  )
}

const indexNestedArray = (arr)=>rf([], indexElements(arr), lengths(arr))

indexNestedArray([["Hello", "World"],["Foo", "Bar"]])
// => [[{"idx": 0, "val": "Hello"}, {"idx": 1, "val": "World"}], [{"idx": 2, "val": "Foo"}, {"idx": 3, "val": "Bar"}]]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46485065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档