Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Foundations Arrays Methods: Part 2

Ireneusz Kopta
Ireneusz Kopta
6,212 Points

Problem

NumArray.sort(function(a-b){ return a-b; }); lessons about arrays method - part 2. How exactly this function works? Cant understand how this function sort numbers in order. if I got array of numbers NumArray=[6,2,7,1,3,7]; How that function put them in order.In my mind if you subtract 2 from 6 you got 4.and so on That its obvious But how does it arrange numbers in order after subtraction?

4 Answers

Cherie Burgett
Cherie Burgett
8,711 Points

alright I'll try and take annother stab at it. So 6-2 = 4 poisitve value means 6 comes after 2 in the sort order. 6-7= -1, six gets moved to before the 7. sort compares the values of a and b, a and be are any of the numbers within your array. It will compare all of the numbers between each other individually and move them either up or down depending on if they return a negaive number or a positive number.

Cherie Burgett
Cherie Burgett
8,711 Points

sorts are run by comparison, if a negative number is returned it is pushed to the front. Is the best way I could explain it. alternatively I believe return a > b ? 1 : a < b ? -1 : 0 would also work to sort an array of numbers.

Ireneusz Kopta
Ireneusz Kopta
6,212 Points

just wonder how the arguments are passed in to function. it takes first two variables and moves em to arguments. Negative number is pushed to the front.Then what? What about the rest of variables.I would like to know the inside process.Sorry I really like to dig what I learn.

Ireneusz Kopta
Ireneusz Kopta
6,212 Points

I was thinking about values ofc :) Thank you for answer!