How to sort array of objects by prev object id in Javascript

混江龙づ霸主 提交于 2020-12-16 04:10:19

问题


I have structure like this:

[
  {id: 1, afterId: -1},
  {id: 5, afterId: 2},
  {id: 2, afterId: 4},
  {id: 4, afterId: 1},
  {id: 3, afterId: 5}
]

Edited

Requirements:

  1. Each object's afterId must be equal to previous object id key;
  2. Object with afterId = -1 must be first;
  3. Should work even if there is duplicated or missing afterId's;

Expected result:

[
  {id: 1, afterId: -1},
  {id: 4, afterId: 1},
  {id: 2, afterId: 4},
  {id: 5, afterId: 2},
  {id: 3, afterId: 5}
]

Example: http://jsfiddle.net/z3sfdo1z/


回答1:


Here is a solution using for loops.

var newList = [];
var afterId = -1;
for (var i = 0; i < list.length; i++) {
  var item;
  for (var j = 0; j < list.length; j++) {
    if (list[j].afterId === afterId) {
      item = list[j];
      break;
    }
  }
  afterId = item.id;
  newList.push(item);
}

http://jsfiddle.net/z3sfdo1z/1/

Starting with -1, loop through the list to place each item in order until all items have been placed. Note that this will fail if the array is missing a specific afterId.




回答2:


Here's a solution that seems to work based on what you started :

list.sort(function(a,b){
     if (a.afterId == -1 || b.afterId == a.id) {
     return -1;
     }
     if (b.afterId == -1 || a.afterId == b.id) {
     return 1;
     }
      return 0;

    });

http://jsfiddle.net/Mouradif/fv9wLz3c/3/



来源:https://stackoverflow.com/questions/27848278/how-to-sort-array-of-objects-by-prev-object-id-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!