Sarathi Hansen Sarathi Hansen - 9 months ago 40
Javascript Question

JavaScript - Sort an array based on another array of integers

Say I have an array:


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?


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.