Hello,
I have a Javascript30 question. Is it ok to post the question here?
Cheers,
Hello,
I have a Javascript30 question. Is it ok to post the question here?
Cheers,
Sure. Weâre kind of built around FCCâs web dev curriculum, but you can bring up other things. Anything that helps people learn to be better coders is gravy.
Thanks Kevin!
I have questions for the following challenge.
This is the answer to the challenge!
The following is my answer to question # 3 of the challenge:
// Array.prototype.sort()
// 3. Sort the inventors by birthdate, oldest to youngest
const inventorsBirthAscending = inventors.sort((previous,current)=>
{
console.log(previous.year)
console.log(current)
return previous.year - current.year})
console.log(inventorsBirthAscending)
It works but the answer is quite different. Looking for some help with whatâs actually going on.
I actually like yours better. It will sort based on positive or negative, regardless of the size of the number. You are generating that through subtraction. They are generating it through returning 1 or -1 depending on which is larger. What you have is simpler. I like simple.
The other issue I have with theirs is that it doesnât account for if they are the same. I would expect it to return 0 in that case - yours does, theirs doesnât. I thought there was an issue if a sort callback didnât deal with that case - I may be wrong. Maybe Iâll run some experiments later.
Iâd also suggest looking at the docs for the sort method, specifically the compare function it takes.
I figured out mine did account for 0. (I tested it)
I did look. My brain blew up a bit. Iâll try again.
With regards to my question about if there was a difference in the two approaches to the sort callback. When in doubt, test it. I wrote a little code to test it, you can see the pen here. Itâs a bit ugly but it gets the job done. (Which coincidentally is how my wife describe me.)
At least in this JS implementation, the difference in speed is very rare and very trivial. Sometimes when I run it, the âusing zeroâ version has a slight advantage, but probably not enough to matter in the astronomically vast number of cases.
This is of course assuming that âfewer calls to the callbackâ is best. It may also be the case that one callback is slightly more performant than the other. But that is a different test and a more complicated one.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.