DEV Community

How does this alphabetical-sorting function work?

David Clark on July 25, 2019

I'm pretty sure I wrote this function based off of someone else's that I saw. Trouble is, I'm looking back through some code, and I don't fully und...
Collapse
 
curtisfenner profile image
Curtis Fenner

.sort is a function in JavaScript. It modifies the list in place, so uniqueSet is also affected by this, not just sortedList. (It just also returns the same list, as a convenience for chaining multiple calls on the array)

You give it a comparison function. The comparison function should behave something like "minus": if the left thing is 'smaller' (you want the left earlier in the list than the right), return a negative number. If the left and right are the same, return 0. If the left is 'bigger', return a positive number.

Your function does this by comparing a and b.

Note that the default is to sort strings in this way. If uniqueSet's elements are strings, you could instead write let sortedList = uniqueSet.sort().

However, for numbers, the default does the wrong thing, as it first converts the numbers to strings (resulting in the confusing "11" < "2"), and you need to write the code that you have here.

Collapse
 
daviddoes profile image
David Clark • Edited

Yes, yes, yes! It's all coming back now.

Follow-up:

Here is the rest of what I'm doing with this data:

    let momentsList = [];
    this.props.moments.forEach(({ id, location }) => momentsList.push({ id, location }));
    let uniqueSet = [...new Set(momentsList.map(moment => moment.location))];

The data being returned, stored in momentsList, and manipulated, is an array of objects (as you can see). Using let sortedList = uniqueSet.sort() worked for it. I think because I'm getting the id and location, then mapping the location.