Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array of objects with specific exceptions in Javascript

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.

like image 540
Andreas Bohman Avatar asked Jul 09 '26 00:07

Andreas Bohman


1 Answers

You should use the following sorting function:

var sorted = a.sort(
    function (a, b) {
        var compareA = a.originalId || a.id;
        var compareB = b.originalId || b.id;

        if (compareA < compareB) {
            return -1;
        } else if (compareA > compareB) {
            return 1;
        } else {
            return a.originalId !== '' ? -1 : 1;
        }
    }
);

An example of the function working is available here.

like image 132
Phylogenesis Avatar answered Jul 10 '26 14:07

Phylogenesis