Skip to content Skip to sidebar Skip to footer

Javascript, Sort Array1 Based On Arry2

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.w

Solution 1:

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]


Solution 2:

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/


Post a Comment for "Javascript, Sort Array1 Based On Arry2"