0

How do I re-order array of object showing below by follow value. If follow value is not -1, move the item below to the item that has the id value same as follow value.

Here is the example.

let charObj = [
  { id: 8, name: 'Catelyn Stark', follow: -1 },
  { id: 7, name: 'Jaime Lannister', follow: 8 },
  { id: 3, name: 'Jon Snow', follow: -1 },
  { id: 4, name: 'Daenerys Targaryen', follow: 7 },
  { id: 5, name: 'Sansa Stark', follow: 4 }
];

Expected output will be;

let charObj = [
  { id: 8, name: 'Catelyn Stark', follow: -1 },
  { id: 7, name: 'Jaime Lannister', follow: 8 },
  { id: 4, name: 'Daenerys Targaryen', follow: 7 },
  { id: 5, name: 'Sansa Stark', follow: 4 },
  { id: 3, name: 'Jon Snow', follow: -1 }
];

Not sure if I can use sort(). What is the best way to re-order this object?

4
  • What happens it two people have the same follow value? The order of that doesn't matter, I suppose? Commented Jul 22, 2020 at 1:33
  • you actually have an array of objects which can be sorted. What are you suppose to do if the follow value is -1? Commented Jul 22, 2020 at 1:36
  • @Narigo move both of them and just keep the order. @DCR -1 does not follow anyone so don't have to do anything. Commented Jul 22, 2020 at 1:38
  • I doubt this is possible through sort() as it would mutate the array on the fly, making it hard to always get the correct index Commented Jul 22, 2020 at 1:55

1 Answer 1

1

I think this will do what you're asking. I'm sure it could be made more efficient, but unless your list gets quite large that shouldn't make much practical difference. Also, this assumes any character will only have one follower. If that's not the rule, then the function will have to be adjusted.

let charObj = [
  { id: 8, name: "Catelyn Stark", follow: -1 },
  { id: 7, name: "Jaime Lannister", follow: 8 },
  { id: 3, name: "Jon Snow", follow: -1 },
  { id: 4, name: "Daenerys Targaryen", follow: 7 },
  { id: 5, name: "Sansa Stark", follow: 4 }
];

function sortChars(chars) {
  let result = [];
  let leaders = chars.filter(c => c.follow === -1);

  for (let i = 0; i < leaders.length; i++) {
    let current = leaders[i];
    while (current) {
      result.push(current);
      let next = charObj.find(c => c.follow === current.id);
      current = next;
    }
  }
  return result;
}

console.log(sortChars(charObj));

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

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.