Skip to content Skip to sidebar Skip to footer

How To Sort Array Of Objects By Prev Object Id In Javascript

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: Each objec

Solution 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.

Solution 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) {
     return1;
     }
      return0;

    });

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

Post a Comment for "How To Sort Array Of Objects By Prev Object Id In Javascript"