Stephen Collins
Stephen Collins

Reputation: 3653

Javascript sort by order of other array

I have a large dataset I need to sort by a preset order. It's simple enough to get the array sorted, but the problem is having the values not in the sort order moving to the bottom instead of the top. Here's my code...

var order = ["value1",  "value2", "value3"];
var result = ["value4", "value2","value1","value1", "value3"].sort(function(a,b) {
    var aIndex = order.indexOf(a),
        bIndex = order.indexOf(b);

    if (aIndex > bIndex)
        return 1;
    if (aIndex < bIndex)
        return -1;
    return 0;
});

...and the fiddle.

I can't figure out how to have a condition that considers something not in the order array to be a lower sort order. I've tried adding if (aIndex < 0 || bIndex < 0) return -1; before the existing conditions, but this will be potentially incorrect of one of the two is in the sort order.

Upvotes: 0

Views: 61

Answers (1)

Pudge601
Pudge601

Reputation: 2068

You could try setting aIndex and bIndex to the length of the order array when they are -1, thus pushing them to the end of the array.

Example in this fiddle: http://jsfiddle.net/a3LfP/1/

Upvotes: 1

Related Questions