freeCodeCamp Challenge Guide: Sort Arrays with Sort

freeCodeCamp Challenge Guide: Sort Arrays with Sort
0

#1

You can use the method sort to easily sort the values in the array alphabetically or numerically

var array = [1,3,2];

array = array.sort();

This will return [1, 2, 3]


#2

But what do we mean by writing
return b-a;
here???


var array = [1, 12, 21, 2];

// Only change code below this line.

array.sort(function(a,b){
  return b-a;
});

This was also my solution to the challenge, but I still don’t understand the logic of writing return b-a.


#3

I’m in the same situartion. I can understand that it works but can’t understand how.


#4

Well, I think I figured it out. Mainly in a mathematics, let’s say we have a set of numbers ( 20, 10, 5, 25) and we want to rearrange them ascending, we pick the first number ( 20 ) and compare it to each other number in the set to check if it is the lowest number in the order criteria until we pick a number is lower than it to put it first in the order. If we didn’t find a lower number so ( 20 ) will be the first number in the order but, if we found a lower number, we replace the 20 with that number and start comparing it with other numbers and repeat this steps till finding the lowest ordered number then we move to the next one. For our example: we will check if 20 < 10 by subtracting them ( 20 - 10 ), and then we have 3 cases for the result:
1- if it is negative so 10 is lower than 20 so 20 replaced by 10 and we start comparing 10 with other numbers.
2- if it is positive so 20 is lower than 10 and it still the first temporary first ordered number.
3- if it is 0 so both are the same value and they remain in the same order. (( not sure that I have said this right ))

by repeating this steps for each number we can order them with specific criteria.

I hope that helped
@sucomimus @Kshitijaa.Jaglan


#5

Thanks a lot @Ahmed-Elbessfy I think I finally got the logic :relieved:


#6

Me too. Thanks @KshitijaaJaglan for setting the question and @Ahmed-Elbessfy for answering it.


#7

I think another explanation is b - a returns largest to smallest BECAUSE: in unicode a comes before b. Therefore a being 1st and b being 2nd. So in other words the array iterates from 2 (being the larger of the two numbers) to 1 (being the lowest) That’s the way that makes the most sens to me at least lol. Hope that helps in some way :smiley:


#8

My take:

var array = [1, 12, 21, 2];

// Only change code below this line.

array.sort(function(a,b) {
return b - a;
});


#9

Common sense. I love this