Sort array containing objects based on another array [duplicate]

We can use the sort() function to do this by passing it a custom function which does the comparison. This function has to return 3 possible values given a or b to compare:

return -1 if a is indexed lower than b

return 0 if a is considered equal to b

return 1 if a is indexed greater than b

With this in mind, we can define a function such as this:

function sortFunction(a,b){
    var indexA = arr.indexOf(a['key']);
    var indexB = arr.indexOf(b['key']);
    if(indexA < indexB) {
        return -1;
    }else if(indexA > indexB) {
        return 1;
    }else{
        return 0;       
    }
}

This function will take in the objects you defined in your array, and find where that value is in the arr array, which is the array you’re comparing to. It then compares the index, and returns the values as needed.

We use this function by passing the function into the sort() function as such:

testArray.sort(sortFunction)

where testArray is the array you’re trying to sort.

You can take a look at here, where I did this example, and you can see the second object in your array being “alerted” to you, before and after the sort function was called. http://jsfiddle.net/Sqys7/

Leave a Comment