TransWikia.com

Javascript re-order array of object by value

Stack Overflow Asked on November 17, 2021

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?

One Answer

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));

Answered by EvanMorrison on November 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP