Extigo
Extigo

Reputation: 99

Sort array using another array in Javascript

I have got an array like this:

[1, Stopped]
[2, Waiting]
[3, Finished]
[4, Stopped]
[5, Running]

The number is the id of the program and the text is the status of the program. I need to sort this array according to the next order:

['Error','Halted','Blocked','Finished','Waiting to Start','Waiting','Stopping','Running','Idle','Stopped','Opened','Ready'];

Can anyone tell me how I can sort the array using the predefined order?

It is working in all different browsers except for IE8. Can anyone tell me how to sort it in IE8

Upvotes: 1

Views: 181

Answers (1)

Minko Gechev
Minko Gechev

Reputation: 25682

You can use this:

if (typeof Array.prototype.indexOf !== 'function') {
    Array.prototype.indexOf = function (el) {
        for (var i = 0; i < this.length; i += 1) {
            if (this[i] === el) return i;
        }
        return -1;
    }
}

var a = [[1, 'Stopped'],
[2, 'Waiting'],
[3, 'Finished'],
[4, 'Stopped'],
[5, 'Running']];
var order = ['Error','Halted','Blocked','Finished','Waiting to Start','Waiting','Stopping','Running','Idle','Stopped','Opened','Ready'];

a.sort(function (a, b) {
   return order.indexOf(a[1]) - order.indexOf(b[1]);
});

Upvotes: 2

Related Questions