I am trying to sort a JavaScript array based on sort order in a second array. I have already gone through other similar questions here in SO and came up with the below code. Be the output is not getting as expected.
var legends = ["Maths","Physics","English","French","Chemistry"];
var sortOrder = [1,400,300,200,-3];
legends.sort( function (a, b) {
return sortOrder[legends.indexOf(a)] >= sortOrder[legends.indexOf(b)];
});
console.log(legends);
The desired output is
["Chemistry", "Maths", "French", "English", "Physics"];
- Chemistry denotes the sort order -3
- Maths next higher count, that is 1
- French next higher count, that is 200
I am trying to get the desired output either in pure JS or using D3js, not sure if I am doing it right!