0

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/

8
  • I'm sorry, question was incorrect (my english is sucks). Maybe with expected result porovided will be better. Commented Jan 8, 2015 at 19:53
  • link shown has all the answers you need though ... stackoverflow.com/questions/1129216/… Commented Jan 8, 2015 at 19:54
  • I wish... Let say I will use sort, and compare objects by id === afterId. If are not equal - I don't know how they are must be ordered relative to one another. If i will return 0, then they will be threatet like equal - witch isn't correct Commented Jan 8, 2015 at 19:59
  • sort will work ... try it and if it isn't working post that code. It is much easier to get help here when you have shown an attempt with real code Commented Jan 8, 2015 at 20:01
  • @charlietfl Thank you for your patience. I change example and add a code snippet, maybe now it will be clear that my question is not duplicate. Commented Jan 8, 2015 at 20:14

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it definetly works as expected, but only if there is no duplicated or missing afterId's. I'm looking for more booletproof solution.
Good luck! :) I'd recommend updating your sample data to include duplicate and missing IDs and also updating the expected results. As it stands, it's not clear what the expected behavior is.
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.