This is the array what I am getting
[
  { id: 1, name: 'hello world', reference_id: null },
  { id: 2, name: 'hello world', reference_id: null },
  { id: 3, name: 'hello world', reference_id: 1 },
  { id: 4, name: 'hello world', reference_id: null },
  { id: 5, name: 'hello world', reference_id: 1 },
  { id: 6, name: 'hello world', reference_id: 2 },
]
I need to reorder this array into something similar to this.
[
  { id: 1, name: 'hello world', reference_id: null },
  { id: 3, name: 'hello world', reference_id: 1 },
  { id: 5, name: 'hello world', reference_id: 1 },
  { id: 2, name: 'hello world', reference_id: null },
  { id: 6, name: 'hello world', reference_id: 2 },
  { id: 4, name: 'hello world', reference_id: null },
]
This is the code which I tried
const parentIndex = skus?.findIndex(item => item.id === item.reference_id);
    console.log(parentIndex)
    if (parentIndex !== -1) {
      const parentId = skus[parentIndex].id;
      const parentItem = skus.splice(parentIndex, 1)[0];
      const referencedItem = skus.find(item => item.id === parentId);
      if (referencedItem) {
        const referencedIndex = skus.indexOf(referencedItem);
        skus.splice(referencedIndex + 1, 0, parentItem);
      } else {
        skus.push(parentItem);
      }
    }
When I run this code I am getting some weird unexpected results and most of the time it's not running after the first line.
Can someone help me to resolve this issue I am struggling to find a solution.
 
     
     
    