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:
arr1.sort(function(i, j){
return arr2[i-1].localeCompare(arr2[j-1])
});
The result is indeed [1, 3, 2, 4]
The arguments in the sort
method are the array items, not their index, so you need to find the index based on the items, assuming the values are unique.
Basic example will be:
var result = arr1.sort(function(i, j) {
return arr2[Find(arr1, i)].localeCompare(arr2[Find(arr1, j)]);
});
Where the Find
function can be:
function Find(arr, key) {
for (var i = 0; i < arr.length; i++)
if (arr[i] == key)
return i;
return -1;
}
Test case: http://jsfiddle.net/tqQDJ/
精彩评论