By utilizing the sort() function, we are able to achieve this by providing it with a custom comparison function. This particular function must yield one of three values based on the comparison between a
and b
:
If a
comes before b
in order, we return -1
If a
is deemed equal to b
, we return 0
If a
follows b
in order, we return 1
To illustrate, we can create a function like so:
function compareValues(a,b){
var indexA = array.indexOf(a['identifier']);
var indexB = array.indexOf(b['identifier']);
if(indexA < indexB) {
return -1;
} else if(indexA > indexB) {
return 1;
} else {
return 0;
}
}
This function takes the objects defined within your array, determines their location in the array
, which serves as the reference for comparison. It then contrasts the indices and produces the necessary output.
To implement this, we supply the function to the sort() function as follows:
dataList.sort(compareValues)
where dataList
denotes the array undergoing sorting.
You can observe a demonstration of this technique in action here, showcasing the second object in your array being showcased both prior to and following the execution of the sorting function. http://jsfiddle.net/Abc123/