Custom Array Sorts in JavaScript

  Рет қаралды 18,209

Steve Griffith - Prof3ssorSt3v3

Steve Griffith - Prof3ssorSt3v3

6 жыл бұрын

This video discusses how you can run sorts on Arrays of Numbers or Arrays of Objects to get the proper results.
The problem with the default Array.sort method is that it converts everything to Strings before doing its comparison.
We can create our own custom sort function to handle non-string sorts.
Code GIST: gist.github.com/prof3ssorSt3v...
See Also: This tutorial on the JavaScript International Object's string compare method for dealing with multilingual sorts.

Пікірлер: 75
@eruston
@eruston 5 жыл бұрын
Fantastic explanation and examples. One thing I might add: the positive (1) result indicates a change in order is needed. The negative (-1) or zero result means no change needed. What I have come to understand is that sort() loops over the array, applying the comparison to each consecutive pair of elements for as many iterations are needed until no changes are needed (all comparisons of consecutive pairs produces a negative result).
@seanpaulson9098
@seanpaulson9098 3 жыл бұрын
@Finance Simply Explained meaning none of the comparisons needed a change. ie they all produced (returned) -1.
@douggreene9669
@douggreene9669 2 жыл бұрын
This is the best explanation I have EVER heard after watching hours of videos about sort. And it was just a couple of sentences. Thank you so much!
@Colstonewall
@Colstonewall 6 жыл бұрын
The absolute best explanation of custom sort I've seen on Y.T. or the internet in general.
@alexhitchins4339
@alexhitchins4339 4 жыл бұрын
I agree with you...this man is fucking awesome!!! He explain so good!!
@NikolasToCore
@NikolasToCore 4 жыл бұрын
Totally agree. No one has explained what is actually happening with a and b, they just saying "do it that way" without explanation. It may seem obvious, but for beginners it may not))
@robbyrish13
@robbyrish13 Жыл бұрын
The precise way in which you articulate this explanation is such a breath of fresh air, especially given the treacherousness of the sea of poorly-worded explanation/tutorial videos on KZbin. Subbed.
@creativestarfox
@creativestarfox 4 жыл бұрын
Best video I found so far explaining this concept. I couldn't grasp how it could sort from low to high numbers at first but now I understand it runs the entire array multiple times until all the values have been compared and put in order.
@WishIWasAMuppet
@WishIWasAMuppet 3 жыл бұрын
Subscribed. This was phenomenal. By far the clearest, most concise explanation of how to do this anywhere on the internets. Keep it up!
@theriddler525
@theriddler525 3 жыл бұрын
This is the best sort() explanation I have found! Excellent
@drakecoleman9364
@drakecoleman9364 3 жыл бұрын
Literally the best explanation for sort. Really. Noone on youtube mentions that it goes through the number list until its fully has it sorted and by using its own sorting method behind the scenes. Thanks for the 100th time Steve, you da man.
@emiklad2594
@emiklad2594 4 жыл бұрын
THIS. IS. SO. AWESOOOOME... Thanks Steve. The knowledge of this alone has added a lot to my JS skill.
@chriscarlsonofficial
@chriscarlsonofficial 4 жыл бұрын
well done, my new javascript textbook flew right over this like it was common knowledge. Thank you.
@hugovallezinzun
@hugovallezinzun 5 жыл бұрын
Finally after hours of finding just bad or wrong explanations, thanks a lot!
@m4ri494
@m4ri494 5 жыл бұрын
Same! I'm surprised by the # of tutorials suggesting that .sort() can sort numerically by default
@KeepLearing
@KeepLearing 4 жыл бұрын
Though there's one more way that is a lot simpler but this guy is a lot more explained/clear! I really like this guy, he's the best!
@prabhupadsahu2276
@prabhupadsahu2276 3 жыл бұрын
I know that I am watching this awesome explanation after 2 years, but Kudos to you and Thank you .
@omare4682
@omare4682 2 жыл бұрын
sir thank you your explination much better than my teacher
@formickaw
@formickaw 2 жыл бұрын
Best explanation of sort method, ever! :)
@rotrose7531
@rotrose7531 4 жыл бұрын
You are all we need to know if we want to excel in javascsript.
@mitrasu5918
@mitrasu5918 3 жыл бұрын
This Voice man... i want Steve's voice to narrate my life...
@tonygriffin944
@tonygriffin944 3 жыл бұрын
Great explanation of sort, well done!
@TechnoDB
@TechnoDB 4 жыл бұрын
Explanation is really handy. Thanks man.
@kamaboko1
@kamaboko1 5 жыл бұрын
Fantastic explanation. Thank you.
@chesterxp508
@chesterxp508 2 жыл бұрын
Another very cool tutorial!
@jamilamini7807
@jamilamini7807 6 жыл бұрын
Dude I subscribed and going to share your videos please don't let me down keep up the good work
@marichkasynoratska2358
@marichkasynoratska2358 3 жыл бұрын
Thanks so much!!! Great explanation!
@gregorio87
@gregorio87 7 ай бұрын
some good movies you got in that array there. oh, and great explanation as well
@gromswift
@gromswift 3 жыл бұрын
That was useful. Thanks!
@krzusiekniwazne
@krzusiekniwazne 6 жыл бұрын
Steve , thank you for the knowledge I acquired from your tutorials. If you find a moment, record something about MutationObserver. All good from Poland
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 6 жыл бұрын
Happy to add that to my list. Please post it here - kzbin.info/www/bejne/gnTIq5SuZ9qBacU - you can also vote for other topics.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 6 жыл бұрын
kzbin.info/www/bejne/iIKUf5J7hZVqrtU - the MutationObserver video will be out tomorrow.
@gautamvallepu5267
@gautamvallepu5267 5 жыл бұрын
Nice video with nice voice
@RedEyedJedi
@RedEyedJedi 4 жыл бұрын
5:20 people === disarray, true at the moment.
@SACHIN-gd6zy
@SACHIN-gd6zy 4 жыл бұрын
awesome video.
@fay1447
@fay1447 4 жыл бұрын
Thanks, Steve
@aravindkumar8145
@aravindkumar8145 3 жыл бұрын
Wow superb
@gahrGoyl
@gahrGoyl 5 жыл бұрын
you rock. thanks so much!!
@blu8762
@blu8762 5 жыл бұрын
thank you so much !
@user-ir2vf2nw6d
@user-ir2vf2nw6d 2 жыл бұрын
The movie's voice sounds not good, but the content is great!
@Heffsta02
@Heffsta02 4 жыл бұрын
Steve should do ASMR videos
@DmitriyMalayevProfile
@DmitriyMalayevProfile 2 жыл бұрын
Thanks
@clydecalador
@clydecalador 4 жыл бұрын
Hi Steve, First of all I'd like to thank you for making such quality videos. Your explanations are by far the best I have ever come across. I have a question which I hope you can help me with. When trying to recreate your example of the sort method, I seem to be getting the second item in the array for 'a' and the first item for 'b'. I find this confusing as in your example - and everywhere else I have seen - 'a' is the first item and 'b' the second. Here is the code: const arr = [22, 4, 66, 77, 5, 4, 2]; const sorted = arr.sort((a, b) => { console.log(`Sorting: ${a} ${b}`); }) Output: "Sorting: 4 22" "Sorting: 66 4" "Sorting: 77 66" "Sorting: 5 77" "Sorting: 4 5" "Sorting: 2 4" Any insight here would be greatly appreciated! Thanks!
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
You can call the two variables anything you want. If the function returns a value less than zero the the value of the first value will be sorted as lower than the second. If the return value from the function is bigger than zero then the first value will be sorted higher. The function will be called repeatedly with different pairs until the sort method understands the sort value for every item in the array.
@imharishsambasivam
@imharishsambasivam 4 жыл бұрын
it can be even shorten as var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a-b}); for ascending order
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
Or even shorter with an arrow function: points.sort((a,b)=>a-b); The main purpose of the tutorial is to help people understand the return values though.
@rovinox
@rovinox 4 жыл бұрын
when you're too lazy to write console.log() every time so you create a variable for that method lol btw awesome video
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
Good programmers are efficiently lazy. 😀
@KL4NNNN
@KL4NNNN 4 жыл бұрын
What does return 1 and return -1 actually mean in this method? true or false? Or it is index position of the number in the element? I quite do not understand
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
A value of zero means that both a and b are equivalent and no changes to the sort or need be made. A value of 1 or more means that a is greater than b and a should be higher in the sort order. A value of -1 or less means that b is greater than a and b should be higher in the sort order.
@DmitriyMalayevProfile
@DmitriyMalayevProfile 2 жыл бұрын
Hello Steve, hope all is well. Question I pass in an array and my console log statements are different. Any feedback appreciated.
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 2 жыл бұрын
Sorry. Don't understand what you are asking.
@DmitriyMalayevProfile
@DmitriyMalayevProfile 2 жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 Got it. Thanks.
@bryangonzales7285
@bryangonzales7285 4 жыл бұрын
What does return 1, 0and -1 do pls kindly elaborate
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
The sort method uses the return value from the function (-1, 0, 1) to decide whether the two values passed into the function need to be reordered.
@singhvimlesh
@singhvimlesh 2 жыл бұрын
Hello Sir can you help me out on this var numArray = [0.44, 0.73, 0.8, 0.9,0.36,47]; and answer shold be [47,0.73, 0.44, 0.36, 0.17, 0.9, 0.8]. how can I sort this ?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 2 жыл бұрын
That is not in numerical order. Is this for some programming test meant to test your logic skills? I can see an answer but I'm not going to write the code for you.
@lycan2494
@lycan2494 4 жыл бұрын
why not do tutorial on how to sort mixed alphabets and numbers
@hamidRaven13
@hamidRaven13 Жыл бұрын
the numbers 1 and -1 and zero is a question for me where did they come from?
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 Жыл бұрын
If you pass a custom function to the sort method, then that function needs to return a number that is positive, negative or zero. The sort method then uses that result to determine how to rank the two items it just compared.
@andremachadomonte
@andremachadomonte 4 жыл бұрын
@Steve Griffith I am trying to create a generic customSort function that I can use with any property field. I am trying to create something like: Object Person = [{name: "Zac", age: 31}, {name: "Andrew", age: 11}]; customSort(arr: any[], property_to_sort: string) { return arr.sort( (a, b) => { if(a.property_to_sort > b.property_to_sort) { return 1;} else if(a.property_to_sort < b.property_to_sort) {return -1;} else {return 0;} }) } I would like to call this function like: person = person.customSort(person, 'name'); PS: THIS DOES NOT WORK!
@seanpaulson9098
@seanpaulson9098 3 жыл бұрын
for the number sort couldnt you just do: numbers.sort((a, b) => a < b);
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 3 жыл бұрын
It wants a numeric result that is zero, or greater than zero, or less than zero. In many cases you can use subtraction to get that numeric result, if you are dealing with comparing numbers. But, if you were dealing with numbers only then the default sort( ) works fine. It all depends on what you are comparing. If you are doing a custom sort then there is a reason you are not using the default sort( ).
@armyteguh2649
@armyteguh2649 5 жыл бұрын
i'm sorry Sir, I have a question Why do You had to Make a three Comparison, isn't "-1" and "0" returning the same Result false, Then What the difference "-1" and "0", Sorry For My bad english... by the way, it's was really very Good explanation, Thanks In Adavance sir...
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 5 жыл бұрын
In terms of Boolean equivalents: 0 is false and all other numbers are true. The sort function can return 1, 0, or -1. 1 means greater than, -1 means less than, and 0 means equivalent values. Further reference - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description
@babythedude
@babythedude 4 жыл бұрын
need to explain what does returning 1 or -1 mean
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
It is measure which of the two values is greater than the other. if a > b then return 1 if b > a then return -1, if they are the same return 0. The sort function is passing in two values at a time to compare them. It will pass in all the different combinations to see how the array should be sorted.
@babythedude
@babythedude 4 жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 Thank you for the explanation, -1 means a will go before b, and 1 means a will go after b
@a9bdvideo
@a9bdvideo 4 жыл бұрын
I am getting the second result first ( 16 then 40) in the console. Any idea why? please let me know. let numbers = [40, 16, 67, 345, 22, 23, 142, 63, 59, 283]; let sortedNum = numbers.sort((a,b) => { log('sorting', a, b); }); sorting 16 40 sorting 67 16 sorting 345 67 sorting 22 345 sorting 23 22 sorting 142 23 sorting 63 142 sorting 59 63 sorting 283 59
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
You have no control over what values are passed into a and b. The sort method decides that as it compares all the values
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 4 жыл бұрын
If you are talking about the final sorted result, it is because everything is compared based on their string character value, not numerical. Which is why we create the custom sort to do other types of comparisons
@a9bdvideo
@a9bdvideo 4 жыл бұрын
@@SteveGriffith-Prof3ssorSt3v3 Thank you so much, teacher. I did not expect you would replay so soon... I am really grateful to you.
@DmitriyMalayevProfile
@DmitriyMalayevProfile 2 жыл бұрын
[28, 6, 22, 8, 44, 17].sort((a, b) => { console.log("sorting", a, b); }); I get sorting 6,28. sorting 22 6, etc
@SteveGriffith-Prof3ssorSt3v3
@SteveGriffith-Prof3ssorSt3v3 2 жыл бұрын
The a and b represent any two of the values from the Array. The sort method decides the order that the elements will be passed to your function. It wants to compare all the necessary combinations. The order it uses will depend on what you are returning from your function.
Practical Uses for Prototypes with Arrays
8:50
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 4,5 М.
ES6 Iterator & Generator Fundamentals
18:18
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 31 М.
Самое Романтичное Видео ❤️
00:16
Глеб Рандалайнен
Рет қаралды 6 МЛН
버블티로 체감되는 요즘 물가
00:16
진영민yeongmin
Рет қаралды 118 МЛН
I Can't Believe We Did This...
00:38
Stokes Twins
Рет қаралды 94 МЛН
NERF WAR HEAVY: Drone Battle!
00:30
MacDannyGun
Рет қаралды 53 МЛН
JavaScript Comparator Function | Sorting Explained!
12:21
The Code Creative
Рет қаралды 32 М.
JavaScript Array filter method
9:15
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 18 М.
Real World Array Method Uses in JavaScript Web Development
24:18
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 12 М.
How sort works in JavaScript
16:19
CJ Avilla
Рет қаралды 3,2 М.
The Differences between ES6 Maps and Sets
6:09
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 7 М.
16.9: Array Functions: sort() - Topics of JavaScript/ES6
9:19
The Coding Train
Рет қаралды 165 М.
JavaScript Array Sort Method Practice in 5 Minutes
7:13
James Q Quick
Рет қаралды 35 М.
Why javascript sort gets so many memes
8:22
Hitesh Choudhary
Рет қаралды 21 М.
Javascript Challenge Sort Array without Built In Step By Step
4:31
JavaScript for..in Loops
7:24
Steve Griffith - Prof3ssorSt3v3
Рет қаралды 43 М.
Самое Романтичное Видео ❤️
00:16
Глеб Рандалайнен
Рет қаралды 6 МЛН