FinitePixels
FinitePixels

Reputation: 33

Sort first array based on second array issue

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!

Upvotes: 3

Views: 68

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386816

You could take a helper array with indices, sort them and map the wanted array.

var legends = ["Maths", "Physics", "English", "French", "Chemistry"],
    sortOrder = [1, 400, 300, 200, -3];

legends = [...legends.keys()]
    .sort((a, b) => sortOrder[a] - sortOrder[b])
    .map(i => legends[i]);        

console.log(legends);

Upvotes: 3

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28475

Try following

var legends = ["Maths","Physics","English","French","Chemistry"];
var sortOrder = [1,400,300,200,-3];

/* Create an array of objects of value index of sortOrder */
legends = Object.entries(sortOrder.reduce((a,v,i) => Object.assign(a, {[v]:i}), {}))
.sort((a,b) => a[0] - b[0]) // Sort array based on sortOrder values
.map(([s, i]) => legends[i]); // fetch items from legends based on sorted order 

console.log(legends);

Upvotes: 1

Francesco
Francesco

Reputation: 4250

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);

Upvotes: 3

Related Questions