1

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

2 Answers 2

2

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]

Sign up to request clarification or add additional context in comments.

Comments

0

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/

1 Comment

Thanks for answering, appreciate it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.