3

I have the following dataset:

var arrayOfObjects = [{
    id: '1',
    name: '1',
    parent: '4'
}, {
    name: '2',
    parent: '1'
}, {
    name: '3',
    parent: '1'
}, {
    id: '4',
    name: '4',
    parent: '5'
}, {
    name: '5',
    id: '5'
}, {
    name: '6'
}];

I would like to convert this array into a new array, where the objects are sorted. The only rule is that the object which has parent can not be on lower index than its parent object.

Possible result:

var resultArrayOfObjects = [{
    name: '5',
    id: '5'
},{
    id: '4',
    name: '4',
    parent: '5'
},{
    id: '1',
    name: '1',
    parent: '4'
},{
    name: '2',
    parent: '1'
}, {
    name: '3',
    parent: '1'
}, {
    name: '6'
}];

The object with name '6' can be anywhere as he is not parent or child of anyone.

What is the preferred algorithm to make this sort happen?

Roland Soós
  • 3,125
  • 4
  • 36
  • 49

0 Answers0