繁体   English   中英

按下一个 id 对双向链表进行排序 Ramda.js

[英]Sort doubly linked list by next id Ramda.js

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

我的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顺序可视化数组中的数据。

PS即使知道本机解决方案也很好,然后我可以尝试自己转换为Ramda.js

原生方法

您可以按id排序并选择最低的id作为所需输出的第一个元素,然后您可以通过使用属性next_id查找下一个节点来推送下一个元素。

 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'}], result = [[...dll].sort((a, b) => a.id - b.id).shift()]; dll.forEach(() => result.push(dll.find(({id}) => id === result[result.length - 1].next_id))); console.log(result);

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

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM