0

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?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Tobias
  • 494
  • 3
  • 14
  • 30
  • 1
    check this out: http://stackoverflow.com/questions/7377730/javascript-arrays-sorting/7377824#7377824 – Andy Sep 29 '11 at 10:10

5 Answers5

2

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);
Jayendra
  • 52,349
  • 4
  • 80
  • 90
1

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

0

Use a custom sort function. Read a documentation how to do it.

kan
  • 28,279
  • 7
  • 71
  • 101
0

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

Narendra Yadala
  • 9,554
  • 1
  • 28
  • 43
0

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):

Community
  • 1
  • 1
JMax
  • 26,109
  • 12
  • 69
  • 88