Custom Array Sorts in JavaScript

แชร์
ฝัง
  • เผยแพร่เมื่อ 3 ต.ค. 2024
  • 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.co...
    See Also: This tutorial on the JavaScript International Object's string compare method for dealing with multilingual sorts.

ความคิดเห็น • 75

  • @eruston
    @eruston 5 ปีที่แล้ว +23

    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 4 ปีที่แล้ว +1

      @Finance Simply Explained meaning none of the comparisons needed a change. ie they all produced (returned) -1.

    • @douggreene9669
      @douggreene9669 3 ปีที่แล้ว

      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!

  • @robbyrish13
    @robbyrish13 2 ปีที่แล้ว +2

    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 TH-cam. Subbed.

  • @Colstonewall
    @Colstonewall 6 ปีที่แล้ว +22

    The absolute best explanation of custom sort I've seen on Y.T. or the internet in general.

    • @alexhitchins4339
      @alexhitchins4339 4 ปีที่แล้ว +1

      I agree with you...this man is fucking awesome!!! He explain so good!!

    • @NikolasToCore
      @NikolasToCore 4 ปีที่แล้ว +3

      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))

  • @creativestarfox
    @creativestarfox 4 ปีที่แล้ว +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.

  • @prabhupadsahu2276
    @prabhupadsahu2276 3 ปีที่แล้ว

    I know that I am watching this awesome explanation after 2 years, but Kudos to you and Thank you .

  • @WishIWasAMuppet
    @WishIWasAMuppet 3 ปีที่แล้ว +1

    Subscribed. This was phenomenal. By far the clearest, most concise explanation of how to do this anywhere on the internets. Keep it up!

  • @chriscarlsonofficial
    @chriscarlsonofficial 4 ปีที่แล้ว +1

    well done, my new javascript textbook flew right over this like it was common knowledge. Thank you.

  • @hugovallezinzun
    @hugovallezinzun 5 ปีที่แล้ว +3

    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

  • @omare4682
    @omare4682 3 ปีที่แล้ว

    sir thank you your explination much better than my teacher

  • @theriddler525
    @theriddler525 4 ปีที่แล้ว +1

    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.

  • @formickaw
    @formickaw 2 ปีที่แล้ว

    Best explanation of sort method, ever! :)

  • @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!

  • @mitrasu5918
    @mitrasu5918 4 ปีที่แล้ว +1

    This Voice man... i want Steve's voice to narrate my life...

  • @emiklad2594
    @emiklad2594 4 ปีที่แล้ว

    THIS. IS. SO. AWESOOOOME... Thanks Steve. The knowledge of this alone has added a lot to my JS skill.

  • @gregorio87
    @gregorio87 10 หลายเดือนก่อน

    some good movies you got in that array there. oh, and great explanation as well

  • @rotrose7531
    @rotrose7531 4 ปีที่แล้ว

    You are all we need to know if we want to excel in javascsript.

  • @TechnoDB
    @TechnoDB 4 ปีที่แล้ว +1

    Explanation is really handy. Thanks man.

  • @chesterxp508
    @chesterxp508 3 ปีที่แล้ว

    Another very cool tutorial!

  • @marichkasynoratska2358
    @marichkasynoratska2358 3 ปีที่แล้ว

    Thanks so much!!! Great explanation!

  • @tonygriffin944
    @tonygriffin944 4 ปีที่แล้ว

    Great explanation of sort, well done!

  • @kamaboko1
    @kamaboko1 5 ปีที่แล้ว +1

    Fantastic explanation. Thank you.

  • @gromswift
    @gromswift 3 ปีที่แล้ว

    That was useful. Thanks!

  • @gautamvallepu5267
    @gautamvallepu5267 5 ปีที่แล้ว +1

    Nice video with nice voice

  • @jamilamini7807
    @jamilamini7807 6 ปีที่แล้ว

    Dude I subscribed and going to share your videos please don't let me down keep up the good work

  • @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 ปีที่แล้ว +1

      Happy to add that to my list. Please post it here - th-cam.com/video/LCezax2uN3c/w-d-xo.html - you can also vote for other topics.

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  6 ปีที่แล้ว

      th-cam.com/video/RQ1N_EP07xs/w-d-xo.html - the MutationObserver video will be out tomorrow.

  • @RedEyedJedi
    @RedEyedJedi 4 ปีที่แล้ว +1

    5:20 people === disarray, true at the moment.

  • @aravindkumar8145
    @aravindkumar8145 4 ปีที่แล้ว

    Wow superb

  • @SACHIN-gd6zy
    @SACHIN-gd6zy 4 ปีที่แล้ว

    awesome video.

  • @蹦太君-o4d
    @蹦太君-o4d 3 ปีที่แล้ว

    The movie's voice sounds not good,
    but the content is great!

  • @Heffsta02
    @Heffsta02 5 ปีที่แล้ว +2

    Steve should do ASMR videos

  • @fay1447
    @fay1447 5 ปีที่แล้ว

    Thanks, Steve

  • @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 ปีที่แล้ว +1

      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.

  • @gahrGoyl
    @gahrGoyl 5 ปีที่แล้ว

    you rock. thanks so much!!

  • @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.

  • @blu8762
    @blu8762 5 ปีที่แล้ว

    thank you so much !

  • @DmitriyMalayevProfile
    @DmitriyMalayevProfile 2 ปีที่แล้ว

    Thanks

  • @hamidRaven13
    @hamidRaven13 ปีที่แล้ว

    the numbers 1 and -1 and zero is a question for me where did they come from?

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  ปีที่แล้ว +1

      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.

  • @seanpaulson9098
    @seanpaulson9098 4 ปีที่แล้ว

    for the number sort couldnt you just do: numbers.sort((a, b) => a < b);

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  4 ปีที่แล้ว

      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( ).

  • @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 ปีที่แล้ว +1

      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.

  • @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!

  • @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 ปีที่แล้ว +2

      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

  • @lycan2494
    @lycan2494 5 ปีที่แล้ว

    why not do tutorial on how to sort mixed alphabets and numbers

  • @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 ปีที่แล้ว +1

      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.

  • @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.

  • @babythedude
    @babythedude 5 ปีที่แล้ว +1

    need to explain what does returning 1 or -1 mean

    • @SteveGriffith-Prof3ssorSt3v3
      @SteveGriffith-Prof3ssorSt3v3  5 ปีที่แล้ว

      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 5 ปีที่แล้ว

      @@SteveGriffith-Prof3ssorSt3v3 Thank you for the explanation, -1 means a will go before b, and 1 means a will go after b

  • @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.

  • @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

  • @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 ปีที่แล้ว +1

      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 ปีที่แล้ว +1

      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 ปีที่แล้ว +1

      @@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 ปีที่แล้ว +1

      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.