--- tags: ironhack, lecture, --- <style> .markdown-body img[src$=".png"] {background-color:transparent;} .alert-info.lecture, .alert-success.lecture, .alert-warning.lecture, .alert-danger.lecture { box-shadow:0 0 0 .5em rgba(64, 96, 85, 0.4); margin-top:20px;margin-bottom:20px; position:relative; ddisplay:none; } .alert-info.lecture:before, .alert-success.lecture:before, .alert-warning.lecture:before, .alert-danger.lecture:before { content:"👨‍🏫\A"; white-space:pre-line; display:block;margin-bottom:.5em; /*position:absolute; right:0; top:0; margin:3px;margin-right:7px;*/ } b { --color:yellow; font-weight:500; background:var(--color); box-shadow:0 0 0 .35em var(--color),0 0 0 .35em; } .skip { opacity:.4; } </style> ![Ironhack Logo](https://i.imgur.com/1QgrNNw.png) # JS | Arrays - Sort and Reverse ## Learning Goals After this lesson you will be able to: - Use advanced array methods such are `sort` and`reverse` - Understand different ways to `compare` elements when implementing `sort` method - Understand some sort algorithms ## Introduction Continuing with our array methods, in this lesson we will review `sort` and `reverse`, and how they can help us when we work with arrays. It is critical to truly understand these methods, and how can make the most of them. ## .sort() Here is where it gets weird. JavaScript sort is by no means easy to understand, but it's one of the few array methods that's much more [difficult to do on your own](http://khan4019.github.io/front-end-Interview-Questions/sort.html). :::info According to MDN, [.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) methods sorts the elements of an array **[in place](https://en.wikipedia.org/wiki/In-place_algorithm)** and returns the array. ::: **The default sort order is according to [string Unicode code points](https://en.wikipedia.org/wiki/Code_point).** ### Sorting Numbers Since `sort()` methods order the values according to string Unicode, if we try to order an array of numbers from lowest to highest we can not just call the function because we will have something like this: ```javascript const numbers = [22, 23, 99, 68, 1, 0, 9, 112, 223, 64, 18]; numbers.sort(); console.log(numbers); // [ 0, 1, 112, 18, 22, 223, 23, 64, 68, 9, 99 ] ``` :::info lecture <span style="font-size:500%">😱</span> ::: :::success The <b>items are **sorted as strings by default**</b> and the reason for that is the method converts elements of the array into strings and then compares them. ::: :eyes: That's why the method ordered elements according to their **Unicode code points**. ### What's behind the scenes :::success The JavaScript `sort` method walks through every element in the array and compares them, based on a default `compare` function, or one that you give it. ::: ```javascript function compare(a, b) { if (a < b) return -1; // a is less than b if (a > b) return 1; // a is greater than b if (a === b) return 0; // a equals b } ``` :::info lecture `compare(a, b)` : - `<0` => `a` avant - `>0` => `b` avant - `0` => pas de changement ::: The `compare` function accepts two elements at a time, often referred to as `a` and `b`. If `a - b > 0`: - `a` is *greater than* `b`. - Switch `b` to be before `a` in the array. If `a - b < 0`: - `b` is *greater than* `a`. - Switch `a` to be before `b` in the array. If `a - b === 0`: - `a` and `b` are the same - Keep `a` and `b` in the same place. --- With array `[22, 23, 68, 0, 9, 1, 99]`: 1. `22 < 23`, they're in the correct order! 2. `23 < 68`, they're in the correct order! 3. `68 > 0`, switch places! 4. `68 > 9`, switch places! 5. `68 > 1`, switch places! 6. `68 < 99`, they're in the correct order! ...and repeat until it sorts the array. --- As a conclusion: if we want to sort numbers in numerical order, we must include in the sort method one parameter: a compare function. The compare function, when we want it in ascending order is as simple as switching places when the first number is higher than the second one. :::info lecture Pour des nombres, ce qui revient à : ```javascript function compare(a, b) { return a - b; } ``` puisque, retournera: - `<0`, si a inférieur à b - `>0`, si a supérieur à b - `0`, si a égal b ::: ```javascript const numbers = [22, 23, 99, 68, 1, 0, 9, 112, 223, 64, 18]; // ES5 numbers.sort(function(a, b) { return a - b; }); // ES6 numbers.sort((a, b) => a - b); console.log(numbers); // [ 0, 1, 9, 18, 22, 23, 64, 68, 99, 112, 223 ] ``` :::info lecture Pour un tri dans l'autre sens : ```javascript function compare(a, b) { return b - a; } ``` ::: And of course, if we want to order our array in reverse numerical order, we just need to change our `compare` function. ```javascript const numbers = [22, 23, 99, 68, 1, 0, 9, 112, 223, 64, 18]; // ES5 numbers.sort(function(a, b) { return b - a; }); // ES6 numbers.sort((a, b) => b - a); console.log(numbers); // [ 223, 112, 99, 68, 64, 23, 22, 18, 9, 1, 0 ] ``` ### Sorting Strings Sorting strings is a bit trickier than numbers. Remember that by default the `sort` method order is according to **string Unicode code points** so, if we want to order by ascending alphabetic order, this is the only case where we don't need to provide a comparison function. :::info lecture Pour trier des chaînes, on peut utiliser la fonction par défault, et donc ne pas spécifier de fonction `compare` : ::: ```javascript const words = ["Hello", "Goodbye", "First", "A", "a", "Second", "Third"]; words.sort(); console.log(words); ``` --- :::info lecture DESC order ::: If we want to sort in descending alphabetical order, then we have two options. #### Option 1 **`.reverse()`** :::info lecture On reverse l'ordre de notre tableau, grâce à `.reverse()` ::: ```javascript const words = ["Hello", "Goodbye", "First", "A", "a", "Second", "Third"]; words.sort().reverse(); console.log(words); // [ 'a', 'Third', 'Second', 'Hello', 'Goodbye', 'First', 'A' ] ``` **A different `compare` function** :::info lecture Ou bien en retournant l'opposé, cf. L4 où on aurait dans l'ordre renvoyé `-1` ::: ```javascript= const words = ["Hello", "Goodbye", "First", "A", "a", "Second", "Third"]; words.sort(function (a, b) { if (a < b) return 1; if (a > b) return -1; return 0; }); console.log(words); // [ 'a', 'Third', 'Second', 'Hello', 'Goodbye', 'First', 'A' ] ``` **We can also sort by different attributes, such as length**. ```javascript= const words = ["Hello", "Goodbye", "First", "A", "a", "Second", "Third"]; words.sort(function (a, b) { if (a.length > b.length) return -1; if (a.length < b.length) return 1; return 0; }); console.log(words); // [ 'Goodbye', 'Second', 'Hello', 'First', 'Third', 'A', 'a' ] ``` :::info lecture Ligne 4: `<0` => a AVANT ssi a est plus long ::: ### Sorting Algorithms There are a lot of algorithms to sort an array. Here we can see how 15 of them perform to sort some elements. :::warning It is important to notice that there is no ideal algorithm because it all depends on the data you are sorting. ::: Check this [Sorting Algorithm Animation Web](https://www.toptal.com/developers/sorting-algorithms) to know more about them. <iframe width="560" height="315" src="https://www.youtube.com/embed/kPRA0W1kECg" frameborder="0" allowfullscreen></iframe> ## .reverse() :::success [Reverse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) method reverses an array in place. The first array element becomes the last, and the last array element becomes the first. ::: :heavy_check_mark: **The `reverse` method transposes the elements of the calling array in place, <b>mutating the array</b>, and returning a reference to it**. ```javascript array.reverse() ``` ### Example ```javascript const arr1 = ['one', 'two', 'three']; const arr2 = arr1.reverse(); console.log(arr1); // ['three', 'two', 'one'] console.log(arr2); // ['three', 'two', 'one'] ``` :::info lecture ATTENTION donc, si l'on veut ne pas muter le tableau, il faudra en faire une copie grâce à [`.slice`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/slice#Syntaxe): ```javascript var arr1 = [1,2,3,4]; var arr2 = arr1.slice().reverse(); console.log(arr1); // [1,2,3,4] console.log(arr2); // [4,3,2,1] ``` ::: This method is useful when you are retrieving data ordered in one way, but you want to show to the users oppositely. ## Summary In this lesson, we learned other array methods. Sort and reverse are powerful methods. Manipulating arrays to get the data we want may just be the most common task you perform in programming. If you need to review these topics, do so because the stronger you are with these data structures, the more efficient you will be as a developer. ## Extra Resources - [MDN Sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) - [Sophisticated Sorting in JavaScript](https://www.sitepoint.com/sophisticated-sorting-in-javascript/) - [Array Methods - super useful](https://javascript.info/array-methods)