Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery sorting by two values is not working and only sorts by first value

I have an array that looks like this

['NAME', 5, '2. Defender', 'FALSE', 'TRUE', 'FALSE', 'undefined']
['NAME', 5, '4. Forward', 'TRUE', 'TRUE', 'FALSE', 'undefined']
['NAME', 5, '2. Defender', 'FALSE', 'TRUE', 'FALSE', 'undefined']
['NAME', 4, '4. Forward', 'FALSE', 'TRUE', 'FALSE', 'undefined']
['NAME', 3, '5. Midfielder', 'FALSE', 'FALSE', 'FALSE', 'undefined']

I am referencing this page on how to sort it, and this is what I have:

array.sort(
    function(a, b) {          
      if (a[1] === b[1]) {
        // Price is only important when cities are the same
        return b[2] - a[2];
      }
      return a[1] < b[1] ? 1 : -1;
  });

It only sorts by the [1] value and will not sort by the secondary [2] value. I thought there might be something wrong with my array, but when I switch things to sort by [2] first, then it sorts by that value fine. Though the goal is to sort by [1] first, and then secondarily sort by [2].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The third array element [2] is a string which you can’t compare by subtraction. Use .localeCompare instead

array.sort((a, b) => a[1] !== b[1] ? a[1] - b[1] : a[2].localeCompare(b[2]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading