Return b.length - a.length;


function findLongestWord(str) {
// Step 1. Split the string into an array of strings
var strSplit = str.split(’ ‘);
// var strSplit = “The quick brown fox jumped over the lazy dog”.split(’ ');
// var strSplit = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”];

// Step 2. Sort the elements in the array
var longestWord = strSplit.sort(function(a, b) {
return b.length - a.length;
/* Sorting process
a b b.length a.length var longestWord
"The" “quick” 5 3 [“quick”, “The”]
“quick” “brown” 5 5 [“quick”, “brown”, “The”]
“brown” “fox” 3 5 [“quick”, “brown”, “The”, “fox”]
“fox” “jumped” 6 3 [“jumped”, quick", “brown”, “The”, “fox”]
“jumped” “over” 4 6 [“jumped”, quick", “brown”, “over”, “The”, “fox”]
“over” “the” 3 4 [“jumped”, quick", “brown”, “over”, “The”, “fox”, “the”]
“the” “lazy” 4 3 [“jumped”, quick", “brown”, “over”, “lazy”, “The”, “fox”, “the”]
“lazy” “dog” 3 4 [“jumped”, quick", “brown”, “over”, “lazy”, “The”, “fox”, “the”, “dog”]

// Step 3. Return the length of the first element of the array
return longestWord[0].length; // var longestWord = [“jumped”, “quick”, “brown”, “over”, “lazy”, “The”, “fox”, “the”, “dog”];
// longestWord[0]=“jumped” => jumped".length => 6

I can’t understand how step 2 works, what the hell is?
how the function really works, and why b.length - a.length?


Step 2 uses the array sort function - the sort function needs a way to compare any two elements of the array at a time to determine their relative ordering so it can put the array in some desired order i.e. it needs to tell if the first element of any pair comes before or after the second element or that their relative order does not matter - it does this using a compare callback function that can be passed to sort

The callback must return 3 kinds of values - a negative number if the first element of the pair should be placed before the second element, a positive number if the first element should be placed after the second element, zero if the relative order of the pair should not be changed

The callback in Step 2 orders two elements a, b by decreasing string length - because

b.length - a.length is:
negative if a is longer than b - this orders a longer string before the shorter string
positive if b is longer than a - this orders a shorter string after the longer string
zero if a and b are of equal length - this says the relative order of two equal length strings should not be changed

Sorting is a vast and deep subject - the basics are not hard to grasp and essential knowledge for every programmer


Ohhh @ppc you beat me to it as I was staring at it to figure it out and give an answer hehe! I’ll add my reply too though, just cause I spent all this time thinking (and Im very new so kind of an effort in making sure I understand this too)

So what step 2 is doing is sorting the array from the longest to the shortest word

Using the sort function on the strSplit array, compare two elements at a time, (a,b)
var longestWord = strSplit.sort(function(a, b)

all I can tell you at this point of my knowledge is that b-a sorts by descending (largest to smallest)
return b.length - a.length;

on the other hand, a-b sorts by ascending (smallest to largest)
So this is saying, sort the array by length in descending order.

It took me way too long to explain my thought process on this lol but I hope it kinda helps along with the info ppc gave.


This example shows the effect of different comparison callbacks on sorting a bunch of numeric strings

function sortstrings() {
const strings=["1", "2", "3", "10", "11", "20", "21", "31", "0100", "01", "02", "03", "010", "001"]

// sort copies of strings array
// default sort order is by increasing Unicode code point values
const strings_default_sort=[...strings].sort()
// sort as strings
const strings_by_dictionary_order=[...strings].sort(lexico_order)
// sort as numbers
const strings_by_numeric_value=[...strings].sort(numeric_order)
// sort by string length
const strings_by_length=[...strings].sort(length_order)

console.log(`strings ${JSON.stringify(strings)}`)
console.log(`default sort ${JSON.stringify(strings_default_sort)}`)
console.log(`lexicographic order ${JSON.stringify(strings_by_dictionary_order)}`)
console.log(`numeric order ${JSON.stringify(strings_by_numeric_value)}`)
console.log(`length order ${JSON.stringify(strings_by_length)}`)


Here are the different compare callbacks

function numeric_order(a, b) {
  return parseInt(a, 10) - parseInt(b, 10)

function lexico_order(a, b) {
  //return a.localeCompare(b)
  return a < b? -1: a > b? 1: 0

function length_order(a, b) {
  return a.length - b.length

This is the output

strings ["1","2","3","10","11","20","21","31","0100","01","02","03","010","001"]
default sort ["001","01","010","0100","02","03","1","10","11","2","20","21","3","31"]
lexicographic order ["001","01","010","0100","02","03","1","10","11","2","20","21","3","31"]
numeric order ["1","001","01","2","02","3","03","10","010","11","20","21","31","0100"]
length order ["1","3","2","10","11","20","21","31","03","01","02","010","001","0100"]

Find the longest word, I satisfy all conditions, but still fail
Find the Longest Word in the String

Thank you so much !!!!


I don’t know why I spent tons of time to read to think about it,
but seems can’t totally understand it, even though I can use it.
facing the kind of situation, what should I do???


You spent tons of time to understand it because it’s not written very intuitively, people are used to less than and greater then yet not to less obvious forms of comparison involving minus symbol. You should be proud and happy that you spent the time getting it and if you do not know how to apply it, I dare you to try and fail. I am proud of you and those who helped you for their eloquent way of explaining! Way to go!


Well, you got me to thinking more about it to understand exactly how the sorting is happening (so please those who do understand it, let me know if Im on track or off base!)

I think the sorting process example in your original post is a bit misleading and makes everything confusing because it seems to only pass through one time and then bam everything is in order, but actually, it keeps iterating over the list until all the elements are in place.

I just saw this video a few days ago about sorting, and it really looks to me like what this function is doing is called a Bubble Sort.


You nailed it! Excellent job!


YaY!!! Thank you! I wasnt sure and don’t want to lead anyone astray cause Im learning too… Glad this topic came up though, cause I have used it just cause its what to use, but this got me to really thinking about why and how it works exactly. Whew!


Are you guys still Asking why you Overthink? You do not,…even though you are learning you think just enough to get and understand fully so for all folks who just want a quickie in coding there are no quickies otherwise the result is potent faeces!!!


This is a good video - it compares various sorting algorithms - bubblesort, insertionsort, quicksort - it shows quicksort is fastest - this suggests bubblesort is less likely to be used in real programs than quicksort as a general sorting algorithm

I would strike one cautionary note regarding sources of programming info - take anything you read or what anyone tells you about programming with a huge grain of salt unless the reliability of the source is well-known and the info has been confirmed by other reliable sources - the internet seems chock full of programming knowledge but it is very very hard to get any programming topic right and even harder to explain it precisely without mathematics


Nah, I dont think so, I mean…for me personally it’s not a matter of the process of thinking ie over thinking things, as much as it is taking the time to really think about concepts to understand the reasoning behind it ie understanding.

It can get frustrating when you know something works, but dont understand why so that you understand when to use it moving forward. Or worse, you’re pretty sure something is supposed to work but it doesnt, and you dont understand why. The thinking part I like though lol I absolutely drove my mother nuts asking “Why?” as a little kid and my curious stage never ended. :laughing:


And in addition test what they say or ask them to email you an example and provide your email.


Yeah, someone actually posted it to the FCC Facebook group, and it just so happens Im in Week3 of CS50x which is about sorting, so it came at a really good time to help me really visualize the sorting methods I just learned.

Im with you on sources… I do find a lot of times either the way something is explained is so convoluted its impossible to understand, or Ill think I have a concept down, but as I read more about it and do more research, realize that some of what I first saw isnt quite right. So I try to check out as much stuff as possible and save any resources that really helped me out, in case they have other tutorials, blogs, vids, whatever Ill also find useful later.