我知道有很多 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/