问题
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 object's afterId must be equal to previous object id key;
- Object with afterId = -1 must be first;
- 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