通过下一个ID Ramda.js对双向链接列表进行排序 [英] Sort doubly linked list by next id Ramda.js

查看:49
本文介绍了通过下一个ID Ramda.js对双向链接列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按 next_id 值对双向链表进行排序.

I want to sort doubly linked list by next_id value.

我的DLL:

const dll = [
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null},
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '14', prev_id: null, next_id: '41'},
]

结果:

const dll_result = [
  {id: '14', prev_id: null, next_id: '41'}, // next item - 41
  {id: '41', prev_id: '14', next_id: '22'}, // next item - 22
  {id: '22', prev_id: '41', next_id: '45'}, // next item - 45
  {id: '45', prev_id: '22', next_id: null},
]

我知道对DLL进行排序可能没有意义,但就我而言,我需要使用 next_id 顺序显示数组中的数据.

I understand that it may not make sense to sort the DLL, but in my case I need to sequentially visualize the data from the array using next_id.

P.S.很高兴知道一个本机解决方案,然后我可以尝试自己转换为Ramda.js

P.S. It would be nice to know even a native solution, and then I could try to convert to Ramda.js myself

推荐答案

通过 id 创建项目索引,找到第一个项目( prev_id === null),然后使用while循环进行迭代,然后将当前对象推入结果数组:

Create am index of items by id, find the 1st item (prev_id === null), and then iterate with a while loop, and push the current object into the result array:

const findStart = R.find(R.propEq('prev_id', null))
const indexById = R.indexBy(R.prop('id'))

const sortByNextId = arr => {
  const index = indexById(arr)
  let current = findStart(arr)
  
  const sorted = []
  
  while(current) {
    sorted.push(current)
    current = index[current.next_id]
  }
  
  return sorted
}

const dll = [
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null},
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '14', prev_id: null, next_id: '41'},
]

const result = sortByNextId(dll)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

这篇关于通过下一个ID Ramda.js对双向链接列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆