0

I am new to StackOverflow so I apologize in advance for not being able to type everything structurally.

I have been trying for some time now to add an identifier to my array to use the .sort() function of javascript to have the array content in alphabetical order. It is also important to not disassociate the amount with the name in the array.

My array contains the following when I use the console.log(result);:

['0.4712', 'ARECIBO']
['0.5041', 'CAGUAS']
['0.4121', 'HUMACAO']
['0.4578', 'MAYAGUEZ']
['0.4785', 'PONCE']
['0.4038', 'SAN JUAN']
['0.4318', 'BAYAMON']

I have read many posts and have seen many users post this type of solution...

result.sort(function(a, b) {
            return b[1] - a[0];
        });
        console.log(result);

Sadly, it does not work for me. I strongly believe that not only is my lack of knowledge an impeding factor, but also my lack of identifier in my array. Therefore, I implore your knowledge to solve this issue. If you can provide a brief explanation as to how the solution works, I would be grateful since it helps me grow and understand what I am doing.

Thank you all!

  • Thank you to the user who answered my question. Again, I am new to this site so I do not know how to tag you, still, thank you. Also, how would I go about making a new array with only the now organized numerical values? – Adnel Figueroa Dec 01 '21 at 16:52

1 Answers1

0

var a = [
  ['0.4712', 'ARECIBO'],
  ['0.5041', 'CAGUAS'],
  ['0.4121', 'HUMACAO'],
  ['0.4578', 'MAYAGUEZ'],
  ['0.4785', 'PONCE'],
  ['0.4038', 'SAN JUAN'],
  ['0.4318', 'BAYAMON']
]
var result = a.sort(function(a, b) {
  return a[1].localeCompare(b[1]); //compare 2 strings alphbetically
});
console.log(result);
Himanshu Singh
  • 1,803
  • 3
  • 16
  • Comparison of the values, if it is needed: `result = arr.sort((a, b) => parseFloat(b[0]) - parseFloat(a[0]));` – IgorZ Dec 01 '21 at 16:41
  • Thank you so much for your answer! – Adnel Figueroa Dec 01 '21 at 16:52
  • @IgorZ Thank you for your answer! I have another question, how would I go about making a new array with only the now organized numerical values? – Adnel Figueroa Dec 01 '21 at 17:14
  • @AdnelFigueroa easy: use a `map` function: `result = arr.sort((a, b) => parseFloat(b[0]) - parseFloat(a[0])); digits = result.map(k => k[0])` – IgorZ Dec 01 '21 at 17:17