We can use the sort () function to do this by passing it a user-defined function that performs the comparison. This function should return 3 possible values โโindicated by a or b for comparison:
return -1 if a indexed below b
return 0 if a is considered equal to b
return 1 if a indexed more than b
With this in mind, we can define a function such as:
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 the objects you define in your array and find where that value is in the arr array, which is the array you are comparing with. Then it compares the index and returns values โโas needed.
We use this function by passing the function to the sort() function as such:
testArray.sort(sortFunction)
where testArray is the array you are trying to sort.
You can look here where I made this example, and you can see that the second object in your array is โwarnedโ to you, before and after the sort function is called. http://jsfiddle.net/Sqys7/
source share