Reputation: 494
I have an array looking like this:
markerArray[i] = [i, title, cat];
this array is within a for loop adding the content dynamic
so the result could be something like this:
markerArray[0] = [0, A title, A];
markerArray[1] = [1, A title new, B];
markerArray[3] = [3, A title, E];
markerArray[4] = [4, A title, A];
So my question is how can I or is it possible to sort the array so that the output would be based on A,B C etc or title or whatever taken from inside the array like this, note that the last (category) is in alphabetic order now:
markerArray[0] = [0, A title, A];
markerArray[1] = [4, A title, A];
markerArray[2] = [1, A title new, B];
markerArray[3] = [3, A title, E];
Is this even possible?
Upvotes: 0
Views: 191
Reputation: 72
You have to use the sort function, available in the Array object. This function/method accepts a custom user function to determine how the elements have to be sorted.
function customSorter( a, b )
{
var comp1 = a[2];
var comp2 = b[2];
return (comp1 < comp2) ? -1 : (comp1 > comp2) ? 1 : 0;
}
var markerArray = new Array();
markerArray[0] = [0, "A title", "A"];
markerArray[1] = [1, "A title new", "B"];
markerArray[3] = [3, "A title", "E"];
markerArray[4] = [4, "A title", "Z"];
markerArray[5] = [5, "A title", "A"];
markerArray.sort( customSorter );
Useful info: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
Upvotes: 1
Reputation: 26601
You could try this kind of stuff:
markerArray.sort(function(a,b){
for (i = 0; i <= 3 ; i++) {
if (a[i] <> b[i]) {
if (a[i] < b[i]) return -1;
if (a[i] > b[i]) return 1;
}
}
return 0;
});
This will try to sort with the first element, if they are identical, it tries to sort with the second one, and so on with the third one.
[EDIT] Adding some interesting links (see other answers too):
Upvotes: 0
Reputation: 52799
try -
var markerArray = new Array();
markerArray[0] = [0, "A title", "A"];
markerArray[1] = [1, "A title new", "B"];
markerArray[3] = [3, "A title", "E"];
markerArray[4] = [4, "A title", "Z"];
markerArray[5] = [5, "A title", "A"];
markerArray.sort(function(a, b) {
var comp1 = a[2];
var comp2 = b[2];
return (comp1 < comp2) ? -1 : (comp1 > comp2) ? 1 : 0;
})
alert(markerArray);
Upvotes: 2
Reputation: 9664
You can pass the compare function as a parameter to Array.sort method and write your comparison logic inside the compare function. See here https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
Upvotes: 0