Help with sorting

const alpha = people.sort((lastOne, nextOne) => {
      const [aLast, aFirst] = lastOne.split(', ');
      const [bLast, bFirst] = nextOne.split(', ');
      return aLast > bLast ? 1 : -1;
    });
    console.log(alpha);

OKay so i need some help with sorting. I don’t understand how an alphabetical value can be compared as a greater or less than value.

In this function, it returns values in alphabetical order. So if aLast>blast then it stays on top of the list otherwise drops a position. So is something with an alphabetical order closer to A greater than as opposed to something closer to Z?

I can see the logic behind it I just need to understand these underworkings to make sense of it. In this particular function, it would seem yes Things that are closer to the opt-in alphabetical order are greater than things below in the order.

You can check the documentation to understand how JavaScript’s sort method works:

The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

okay so

Blockquote

Ascending and descending order in Javascript

The sort() method sorts the elements of an array. The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down). By default, the sort() method sorts the values as strings in alphabetical and ascending order. This works well for strings (“Apple” comes before “Banana”).

Blockquote

So even though the list is vertically down it is [0][1][2][3][4][5] is ascending Alphabetical order.

So z>a.

Thats why A is at the top of my list and Z at the bottom, the list is in ascending alphabetical order. But the list itself is going verticlaly down which means the top item would have the “smallest value”. Does that does correct?

I don’t understand what you mean by “vertically down”, but everything else sounds correct.

You can check the numbers that the letters are converted to with charCodeAt:

const string = 'ABab';

console.log(string.charCodeAt(0)) // A converts to 65
console.log(string.charCodeAt(1)) // B converts to 66
console.log(string.charCodeAt(2)) // a converts to 97
console.log(string.charCodeAt(3)) // b converts to 98

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.