I did the following in javascript:
var arr1 =[1,2,3,4];
var arr2 =["ac", "bc", "ad", "e"];
var result = arr1 .sort(function(i, j){return arr2[i].localeCompare(arr2[j])})
document.write(result );
my intention was to sort array1 based on array2. I was expecting the result to be 1,3,2,4, but as it turns out it is 2,1,3,4 can anyone figure out why? Thanks
Arrays are 0-indexed, so your sort function starts comparing with the second and all the way through the fifth; ignoring the first element and the fact that there is no 5th element.
Inserting a -1 in the sort function should fix it:
The result is indeed
[1, 3, 2, 4]