skip to Main Content

I have an unsorted objects array with strings like this:

const unsortedArr =  [
  {
  id: "test13",
  startAfter: "test15"
  },
  {
  id: "test20",
  startAfter: "test5"
  },
  { 
  id: "test5",
  startAfter: "test1"
  },
  {
  id: "test15",
  startAfter: "test20"
  },
]

You get the idea.

I also have a start ID: const startId = "test1";

With my start ID as the first value, I want to sort the array according to the "startAfter" property. Create a chronological chain, so to speak.

The result should look like this:

const sortedArr =  [
    {
    id: "test5",
    startAfter: "test1"
    },
    {
    id: "test20",
    startAfter: "test5"
    },
    {
    id: "test15",
    startAfter: "test20"
    },
    {
    id: "test13",
    startAfter: "test15"
    },
    ]

What is the easiest way to sort this array in JS?

2

Answers


  1. What you have is a linked list, but it lacks the possibility to locate an object by id in constant time. So I’d suggest creating a Map for that first, and then you can create the sorted array by looking up the next id from the current node:

    function sort(unsortedArr, startId) {
        const map = new Map(unsortedArr.map(o => [o.startAfter, o]));
        const sorted = [];
        for (let node = map.get(startId); node; node = map.get(node.id)) {
            sorted.push(node);
        }
        return sorted;
    }
    
    // Example run
    const unsortedArr = [{id: "test13",startAfter: "test15"},{id: "test20",startAfter: "test5"},{ id: "test5",startAfter: "test1"},{id: "test15",startAfter: "test20"},];
    const startId = "test1";
    const sorted = sort(unsortedArr, startId);
    console.log(sorted);
    Login or Signup to reply.
  2. You can achieve this by creating a map of the array and then iterating over the map starting from the startId

    const sortArray = (unsortedArr, startId) => {
        // Create a map for quick lookup
        const map = new Map(unsortedArr.map(i => [i.id, i]));
    
        // The sorted array
        let sortedArr = [];
        let currentId = startId;
    
        while(map.has(currentId)) {
            // Get the item from the map
            const { id, startAfter } = map.get(currentId);
    
            // Add the item to the sorted array
            sortedArr = [...sortedArr, { id, startAfter }];
    
            currentId = startAfter;
        }
    
        return sortedArr;
    }
    
    // Usage
    const unsortedArr = [
        { id: "test13", startAfter: "test15" },
        { id: "test20", startAfter: "test5" },
        { id: "test5", startAfter: "test1" },
        { id: "test15", startAfter: "test20" },
    ];
    
    const startId = "test1";
    
    const sortedArr = sortArray(unsortedArr, startId);
    
    console.log(sortedArr);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search