I've got an array of objects where some of the elements are clones of another, hence they have a property that references another property of the original (simplified example):
var a = [{
id: 'x0',
name: 'Foo',
isClone: false,
wasCloned: true,
originalId: ''
}, {
id: 'y1',
name: 'Bar'.
isClone: false,
wasCloned: false,
originalId: ''
}, {
id: 'z2',
name: 'Foo',
isClone: true,
wasCloned: false,
originalId: 'x0'
}];
In this example, the third element references the id of the first - which makes it a clone in that sense. Unfortunately, the id's are not incremental/chronological and can basically be any random string.
Now, the task at hand is to sort the array in such a fashion so that the clones are always placed on the array position right before the position of its original. If the array element is not a clone, the ordering should proceed as usual. In other words, once sorted, the order in this example would be 2,0,1.
I've tried to figure out how to use Array.sort
for this, but can't really wrap my head around it. This is basically what I've got (which doesn't work):
var sortedA = a.sort(function(one, other) {
var sorted;
if (one.id == other.originalId) {
sorted = -1;
} else {
sorted = 0;
}
return sorted;
});
Any help on this would be much appreciated, thank you.