Sort an array based on another array of integers

You can do something like this:

function getSorted(arr, sortArr) {
  var result = [];
  for (var i = 0; i < arr.length; i++) {
    console.log(sortArr[i], arr[i]);
    result[i] = arr[sortArr[i]];
  }
  return result;
}
var arr = ["one", "two", "three", "four", "five", "six"];
var sortArr = [0, 3, 4, 2, 5, 1];
alert(getSorted(arr, sortArr));

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.

Leave a Comment