JavaScript Comparator Function | Sorting Explained!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everybody in this video we're going to take a look at the comparator function in JavaScript the comparator function is the function that gets passed into JavaScript in build sort function in what it allows us to do is it allows us to really take control of JavaScript stored function to do things beyond just the sorting strings in ascending order when we pass in a comparator function we can do things like sorting numbers in the correct order we can sort the properties on objects and much more so let's get into the code so we can start out here nice and easy by looking at the default behavior of JavaScript sort method as you can see here I have a array of letters and you can see right now that they're unsorted so in order to sort these letters all we'd have to do is say letters dot sort and then let's assign this to a variable well sign it to a constant will say sorted letters equals letters dot sort and then let's log this to the console so we can see what we get so I'm going to go ahead and open my terminal and let's run this code and there we can see our letters are now in sorted order a b c and p at the end now with letters like this letters that are all in the same case in this case they're all lowercase this works just perfectly however let's try something instead of a lowercase P here let's make this an uppercase P let's save it and now again let's log this to the console and check it out here no longer is the P at the end of the array but now it's at the beginning so we have capital P and then lowercase a B and C so why would this be the case well before we go any further we're gonna find out something very important to understanding the sort method if we look at the mdn web docs for the sort method we can see that the default sort order is ascending and the way that it works is that it converts the elements in the array into strings and then here's the important part it compares their sequences of utf-16 code unit values or their unicode values so in this case the way that these letters are being sorted is that they're utf-16 character codes are gotten first and then those are sorted in ascending order so what I'd like to do is I'd like to use a for each loop and log out the character code for each of these values just to help clarify our understanding of what's going on here so let's say letters dot for each and then we'll say for each letter let's log out the letter dot care code at and will say at zero because each of these string elements only have one character so the zero index will be the character itself and actually just to make it that much clearer let's first log out the letter itself and we'll give it a space followed by its character code so let's clear the console and log that out and here we can see each of the elements of RA be the capital P the C and the a followed by the character codes which they're assigned and now we can understand actually how this array is sorted we can see that the P has a character code of 80 and 80 being the lowest value amongst these character codes we could see why it would come first when we store this array so with this knowledge in hand I think we're much better equipped now to understand how sorting in JavaScript works so our next example here is where we're really going to start taking a look at the comparator function so what we're going to do is we're going to make an array of numbers and we're gonna have a 2 a 5 a 104 so let's start out by simply sorting or using the sort method on the numbers array saikhan sorted numbers equals numbers dot sort and let's log this out to the console to see what we get and here where you might have thought that we would have gotten 2 4 5 and 100 and said you can see that we're actually getting the 100 first and then the 2 and the 4 on the 5 and since I've already showed you that JavaScript sort method converts the elements into their character codes first this should explain why this sorting has occurred in this way so once again let's go ahead and let's do a for each on the numbers array and check out the character codes for each of these elements so we're gonna log out each of these numbers to the console along with their character codes so we can see what's going on here so first we'll do the number and then in order to use the care code app method on these numbers we're going to need to convert them into strings first because the care code app method works on strings so we'll say care code at and again we're going to pass in a 0 here and then let's log this to the console and again this explains why the numbers were sorted in the way that we saw before with the 100 being the first element in the sorted array as you can see the one in the number 100 has a character code of 49 which is the lowest number in the set of numbers or the set of character codes so now obviously what we want is we want the 100 to be at the end of the sorted array so this is what we can do to solve this problem let's uncomment out our numbers thought sort here and what we're going to do is we're actually going to pass in a function and this is going to be the comparator function we're going to pass that into the sort method so let's write this like an arrow function here and the way that this comparator function works is it's going to take an a value and a b value so initially that a value is going to be the two in the B value is going to be the five and this comparator function is going to do a 3-way comparison what that means is it's going to check to see whether the a value is less than greater than or equal to the B value so if the a value is less than the B value which it is here then the a value is going to come before the B value if the a value happens to be greater than the B value well then the B value is going to come before the a value for example with these two 100 and the 4 if this was the a value 100 well in this case the a value is greater than the B value so we're gonna want to swap these around we're gonna want to put the B value to come before the a value the 100 in this case and finally if a and B are the same so if we had like a 2 and a 2 well we would just leave a and B unchanged so what we could do is we could come in here into the comparator function and we could say if a is less than B return negative 1 else if a is greater than B return 1 else return 0 and here the comparator function is going to be looking for either a negative value a positive value or a 0 if a negative value is returned then a will come before B if a positive value is returned and B will come before a and if 0 is returned they'll just be left unchanged so now let's console dot log out sorted numbers and we get so let's clear the console and now we can see our numbers here are correctly sorted 2 4 5 and 100 and what if we wanted to sort this array in reverse order well what we could do is we could simply reverse these we could say if a is greater than B return negative 1 and if a is less than B returned positive 1 so now let's log that out to the console and here you can see they are sorted correctly in reverse order with 100 at the beginning of the array but let's put that back to where it was before to produce the correct ascending order and what you should take note of is that it's not important that these return negative 1 and positive 1 but rather that they simply returned either a negative number or a positive number or a 0 so with that in mind we could actually shorten up this comparator function and we could simply return the result of evaluating a minus B and why should that work well let's take a look at it so if a starts out as being to the first element in the array and then we subtract 5 from it that's going to result in a negative value in this case a negative 3 and as we saw before if we get a negative value while then a will come before B let's take the case where we had 100 minus 4 well 100 minus 4 gives us 96 which is a positive value and as we mentioned if we have a positive value well that means that a is greater than B and therefore we need to swap them so that becomes before a so let's verify that this works we'll log it out and we'll see that it's sorted correctly in ascending order and then of course to produce a descending order we could do B minus a and log that out and here we get the correct descending order now that we've seen how to use a comparator function to sort numbers we can move on to an example where we want to sort the properties of an object so let's get rid of all this here and I have an array here of AB in this array is an array of spice girls each object with the name of the spice girl and her age I just made up these ages so I'd add that they're actually these ages but you can see that we have four objects in the array each with a name and an age property so let's say first of all that we wanted to sort this array to have age in ascending order so here's how we can go about doing that let's take our array spice girls and let's use the sort method and we're going to pass it a comparator function in this case let's pass in comparator and we're actually gonna write that function separately here so we'll say Kant's comparator it's going to equal an arrow function and it'll take an A and a B and remember how we use the comparator before to sort numbers well in this case we can do something very similar but since we have properties on on object we're gonna access them like this we're gonna say a dot H minus B dot H so in other words a would be like this 37 B would be the 30 and so on and now let's go in console dot log this to see if we've done this correctly and here we can see that each of these spice girls has been sorted in ascending order by age so 19 20 30 and 37 and now let's try this instead of simply sorting these by name let's sort them by the length of the name so that the shortest name will come first and the longest name will come last and just for some variation because we have these names which have a length of 6 and these names which have a length of 4 instead let's put in scary here to get a name with the length of 5 and let's see if we can sort these now by length so really length is just a number so as long as we're accessing the length property on each of these names here we should be able to use this exact same comparator function so instead of a dot age let's say a dot name dot length minus B dot name dot length and let's try logging that out and here you can see that we've got baby with the length of 4 Posche with the length of 4 scary has a length of 5 and ginger has a length of 6 so as you can see we got the result that we wanted so thanks for checking out this video on the comparator function in JavaScript hopefully in this video you learned how you can use the comparator function to really customize your sort method and go beyond just the default ability to sort strings in ascending order so thanks for checking out this video if you feel like you got something out of it please give it a like and consider subscribing to the channel I'll see you next time
Info
Channel: The Code Creative
Views: 32,531
Rating: undefined out of 5
Keywords: sort javascript, sort js, sort, javascript sort, sorting objects, javascript problem sorting an array of objects, how to sort in javascript, javascript sorting an array, javascript algorithm, sort an array, sort an array of objects, javascript sort by length, javascript sort explained, comparator function, javascript comparator, javascript compare function, javascript sort not working, javascript how to sort numbers, gregg fine, the code creative, javascript for beginners
Id: kxUNQtheCxM
Channel Id: undefined
Length: 12min 21sec (741 seconds)
Published: Mon Apr 13 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.