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

标签 javascript arrays sorting doubly-linked-list 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 按顺序可视化数组中的数据。

P.S. 如果知道一个原生解决方案就好了,然后我可以尝试自己转换为 Ramda.js

最佳答案

通过id创建项目索引,找到第一个项目(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>

关于javascript - 按下一个 id 对双向链表进行排序 Ramda.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60297661/

相关文章:

javascript - 使用 addTextTrack() 动态更改 videojs 字幕

javascript - 如何通过函数向类提供选项列表?

python - 排序和唯一与集合

python - 当 Python 列表中有多余字符时进行匹配

linq - 除级联时,LINQ Quicksort不稳定

javascript - 如何插入或获取内容控件、Outlook Web 插件 JavaScript?

javascript - 将查询参数从 AJAX get 调用传递到快速路由

java - java中使用Arraylist的动态二维数组

arrays - JS 如何在数组中查找字符串中最长的单词

php - PHP 的 count() 函数是 O(1) 还是 O(n) 用于数组?