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 understand how it works.
What I have is a Set
that I'm sorting alphabetically. That Set is named, aptly, uniqueSet
. Here's the code:
let sortedList = uniqueSet
.sort((a, b) => {
if (a < b) return -1;
else if (a > b) return 1;
return 0;
})
Top comments (2)
.sort
is a function in JavaScript. It modifies the list in place, souniqueSet
is also affected by this, not justsortedList
. (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
andb
.Note that the default is to sort strings in this way. If
uniqueSet
's elements are strings, you could instead writelet 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.Yes, yes, yes! It's all coming back now.
Follow-up:
Here is the rest of what I'm doing with this data:
The data being returned, stored in
momentsList
, and manipulated, is an array of objects (as you can see). Usinglet sortedList = uniqueSet.sort()
worked for it. I think because I'm getting theid
andlocation
, thenmap
ping thelocation
.