javascript - 按下一篇文章对文章列表进行排序

标签 javascript algorithm sorting

我知道有很多 sort 相关问题,但我找不到解决方案。

我有这样的数据:

const list = [
  {
    name: 'one',
    next: 'two'
  },
  {
    name: 'three',
    next: 'four'
  },
  {
    name: 'four',
    next: 'five'
  },
  {
    name: 'two',
    next: 'three'
  },
]

我想根据 next 属性对它们进行分类。

我不想按字母顺序排序。但由下一个属性决定。

如果a.next === b.name,那么他先来。

我尝试过这个:

list.sort((a, b) => {
 if (a.next === b.name) {
   return -1
 }
})

我怎样才能实现这个目标?

我想要的结果:

list = [
      {
        name: 'one',
        next: 'two'
      },
      {
        name: 'two',
        next: 'three'
      },
      {
        name: 'three',
        next: 'four'
      },
      {
        name: 'four',
        next: 'five'
      }
    ]

最佳答案

假设数组可以根据所需逻辑进行排序。您可以:

您可以使用reduce 将数组组织成一个对象。通过检查名称是否不存在作为下一个来获取第一个元素。使用经典的 for 循环数组的长度。

const list = [{"name":"one","next":"two"},{"name":"three","next":"four"},{"name":"four","next":"five"},{"name":"two","next":"three"}];

const order = list.reduce((c, v, i) => Object.assign(c, {[v.name]: v}), {}); //Make an order object. This will make it easier to get the values. Use the name as the key
let key = Object.keys(order).find(o => !list.some(x => x.next === o));  //Find the first element. Element that is not found on next

let result = [];
for (i = 0; i < list.length; i++) {  //Loop thru the array. Get the value from order object. 
  result.push(order[key]);           //Push the array from the object order
  key = order[key].next;             //overide the key with the next
}

console.log(result);

关于javascript - 按下一篇文章对文章列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51139157/

相关文章:

javascript - 将 PHP 变量传递回 ajax

javascript - JavaScript 中按特定键对对象数组进行排序的最紧凑方法是什么,其中排序顺序是在数组中定义的?

PHP - 按键长度对哈希数组进行排序

php - 如何从其他关联数组创建关联数组?

c - 尝试按降序合并链表

python - 如何在Python 3.x中获得类似2.x的排序行为?

java - 对按降序排序的 int 数组使用二进制搜索

javascript - 如果有条件,用 php 显示 javascript 结果

javascript - chart.js 响应条形图标签大小

javascript - jQuery 可排序——仅在拖动时启用可排序,而不是单击