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"];
I am trying to get the desired output either in pure JS or using D3js, not sure if I am doing it right!
You are almost right but in the sort function, you refer to legends array which is being mutated, so indexes does not match to original order.
To demonstrate that this is the case, you could copy the array and sort the copy:
var legends = ["Maths","Physics","English","French","Chemistry"];
var legendsToSort = ["Maths","Physics","English","French","Chemistry"];
var sortOrder = [1,400,300,200,-3];
legendsToSort.sort( function (a, b) {
return sortOrder[legends.indexOf(a)] >= sortOrder[legends.indexOf(b)];
});
console.log(legendsToSort);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With