Sarathi Hansen Sarathi Hansen - 3 months ago 8
Javascript Question

JavaScript - Sort an array based on another array of integers

Say I have an array:

[0,3,4,2,5,1]


What i want to do is sort an array such as:

["one", "two", "three", "four", "five", "six"]


so that the order corresponds to the first array.

This would be the output:

["one", "four", "five", "three", "six", "two"]


Is there an easy way to accomplish this?

Answer

You can do something like this:

function getSorted(arr, sortArr) {
  var result = [];
  for(var i=0; i<arr.length; i++) {
    result[i] = arr[sortArr[i]];
  }
  return result;
}

You can test it out here.

Note: this assumes the arrays you pass in are equivalent in size, you'd need to add some additional checks if this may not be the case.

Comments