Sort an array of arrays with strings in it

I am trying to sort an array with an array of strings in it. This seems like this problem ( Sorting an array with arrays in it by line ), but I was not sure how to implement this. My array is as follows

var myArray = [
            ['blala', 'alfred', '...'],
            ['jfkdj', 'berta', '...'],
            ['vkvkv', 'zimmermann', '...'],
            ['cdefe', 'albert', '...'],
          ];

I am trying to sort it alphabetically (case insensitive) by name or second argument for internal arrays. After that, I want to sort by the first argument if there are two elements with the same second argument. I tried to use the following, but was unsuccessful and did not understand why. Can anyone advise:

function Comparator(a,b){
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}

var myArray = [
            ['blala', 'alfred', '...'],
            ['jfkdj', 'berta', '...'],
            ['vkvkv', 'zimmermann', '...'],
            ['cdefe', 'albert', '...'],
              ];

myArray = myArray.sort(Comparator);

To sort the first argument after the second argument, will I do this?

   function Comparator(a,b){
    if (a[1] < b[1]){ 
 if (a[2] < b[2]) return -1
 if (a[2] > b[2]) return 1;
}
return -1;
}
    if (a[1] > b[1]) return 1;{
    if (a[2] < b[2]) return -1
      if (a[2] > b[2]) return 1;
  }
return 1;
  }
return 0;
    }

    var myArray = [
                ['blala', 'alfred', '...'],
                ['jfkdj', 'berta', '...'],
                ['vkvkv', 'zimmermann', '...'],
                ['cdefe', 'albert', '...'],
                  ];

    myArray = myArray.sort(Comparator);
+4
1

:

function Comparator(a, b) {
    // you can use the `String.prototype.toLowerCase()` method
    // if the comparison should be case insensitive
    if (a[1] < b[1]) return -1;
    if (a[1] > b[1]) return 1;
    if (a[0] < b[0]) return -1;
    if (a[0] > b[0]) return 1;
    return 0;
}

, . , , a[1] === b[1] a[0] === b[0] 0, a b .

MDN Array.prototype.sort:

compareFunction, . a b , :

  • compareFunction(a, b) 0, a , b, .. a .
  • compareFunction(a, b) 0, a b , . . ECMAscript , (, Mozilla, 2003 ) .
  • compareFunction(a, b) , 0, b , a. compareFunction(a, b) a b . , undefined.
+3

All Articles