From 1a192e26b2145c345f97b4faacd8c3a267bceb79 Mon Sep 17 00:00:00 2001 From: Sriparno Roy Date: Thu, 11 Sep 2025 21:02:42 +0530 Subject: [PATCH 1/3] [Edit] JavaScript: .sort() --- .../concepts/arrays/terms/sort/sort.md | 102 +++++++++++----- content/javascript/concepts/sort/sort.md | 112 ------------------ 2 files changed, 71 insertions(+), 143 deletions(-) delete mode 100644 content/javascript/concepts/sort/sort.md diff --git a/content/javascript/concepts/arrays/terms/sort/sort.md b/content/javascript/concepts/arrays/terms/sort/sort.md index 9c22e85cd3e..9c694d016e5 100644 --- a/content/javascript/concepts/arrays/terms/sort/sort.md +++ b/content/javascript/concepts/arrays/terms/sort/sort.md @@ -1,68 +1,108 @@ --- Title: '.sort()' -Description: 'Returns an array with its items sorted in place.' +Description: 'Sorts the elements of an array in place.' Subjects: - - 'Web Development' - 'Computer Science' + - 'Web Development' Tags: - 'Arrays' - - 'Comparison' - 'Functions' - 'Methods' - - 'Sort' - - 'Unicode' + - 'Values' CatalogContent: - 'introduction-to-javascript' - 'paths/front-end-engineer-career-path' --- -The **`.sort()`** method returns an array with its items sorted in place. +The JS **`.sort()`** [method](https://www.codecademy.com/resources/docs/javascript/methods) is used to sort the elements of an array in place. By default, it sorts elements as [strings](https://www.codecademy.com/resources/docs/javascript/strings) in ascending order. However, a custom comparison [function](https://www.codecademy.com/resources/docs/javascript/functions) can be provided to achieve more advanced sorting. -## Syntax +## JS `.sort()` Syntax ```pseudo -// No parameters -array.sort(); - -// With optional function -array.sort((firstElement, secondElement) => { /* function body */ }; +arr.sort(compareFn) ``` -If the `.sort()` method is used with no arguments, all items with `undefined` values are shifted to the end of the array while the remaining items are converted to [strings](https://www.codecademy.com/resources/docs/javascript/strings) and sorted by [Unicode code point value](https://en.wikipedia.org/wiki/Code_point). +**Parameters:** + +- `compareFn` (Optional): A function that defines the sort order. It takes two arguments, `a` and `b`, and should return: + - A negative value if `a` should come before `b` + - `0` if `a` and `b` are considered equal + - A positive value if `a` should come after `b` -An optional function is used to define how items are sorted. This is done by iterating over the `array` and comparing every `firstElement` and `secondElement` in the `/* function body */`. +**Return value:** -## Example +JS `.sort()` returns the original array with its elements sorted in the given order. -In the following example, the `.sort()` method is applied to two arrays, `letters` and `numbers` (a mix of floats and integers): +## Example 1: Sorting Array of Strings Using JS `.sort()` + +This example uses JS `.sort()` to sort an array of strings: ```js -const letters = ['d', 'b', 'e', 'a', 'c']; -const numbers = [5, 2, 123, 5.01, 43.5]; +const fruits = ['banana', 'apple', 'cherry', 'date']; + +fruits.sort(); -console.log('Letters: ', letters.sort()); -console.log('Numbers: ', numbers.sort()); +console.log(fruits); ``` -This results in the following output: +Here is the output: ```shell -Letters: [ 'a', 'b', 'c', 'd', 'e' ] -Numbers: [ 123, 2, 43.5, 45, 5, 5.01 ] +[ 'apple', 'banana', 'cherry', 'date' ] ``` -The `letters` were sorted in alphabetical order. The items in `numbers` were sorted based on the leading number in the item's value (e.g., their Unicode value). Sorting numerical values more strictly requires a custom comparison function. +## Example 2: Sorting Array of Numbers Using JS `.sort()` -## Codebyte Example +This example uses JS `.sort()` with a comparison function to sort an array of numbers: + +```js +const numbers = [10, 5, 20, 1, 100]; + +numbers.sort((a, b) => a - b); + +console.log(numbers); +``` + +Here is the output: + +```shell +[ 1, 5, 10, 20, 100 ] +``` -The following example showcases how the optional `callback` argument can be used to sort a `numbers` array in ascending and descending order: +## Codebyte Example: Sorting Array of Objects Using JS `.sort()` + +This codebyte example uses JS `.sort()` to sort an array of objects: ```codebyte/javascript -const numbers = [5, 2, 123, 5.01, 43.5]; +const users = [ + { name: "Alice", age: 25 }, + { name: "Bob", age: 20 }, + { name: "Charlie", age: 30 } +]; + +users.sort((a, b) => a.age - b.age); + +console.log(users); +``` + +## Frequently Asked Questions + +### 1. How do I sort numbers in descending order using JS `.sort()`? + +You can reverse the comparison in your function in JS `.sort()` to sort numbers in descending order: -const ascending = numbers.sort((a, b) => a - b); -console.log("Ascending order: ", ascending); +```js +numbers.sort((a, b) => b - a); +``` + +### 2. Does JS `.sort()` modify the original array? + +Yes. JS `.sort()` performs in-place sorting, meaning the original array is modified instead of creating a new one. -const descending = numbers.sort((a, b) => b - a); -console.log("Descending order: ", descending); +### 3. Can I sort strings in reverse alphabetical order using JS `.sort()`? + +Yes, you can sort strings in reverse alphabetical order using JS `.sort()` with `.reverse()`: + +```js +fruits.sort().reverse(); ``` diff --git a/content/javascript/concepts/sort/sort.md b/content/javascript/concepts/sort/sort.md deleted file mode 100644 index d8b3d75b43c..00000000000 --- a/content/javascript/concepts/sort/sort.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -Title: 'Sort' -Description: 'Sorts the contents of an array and returns the sorted array. This sorting is done in place and affects the original array.' -Subjects: - - 'Web Development' - - 'Computer Science' -Tags: - - 'Arrays' - - 'Methods' - -CatalogContent: - - 'introduction-to-javascript' - - 'paths/front-end-engineer-career-path' ---- - -In JavaScript, the **`.sort()`** method of an array sorts the contents of an array and returns the sorted array. This sorting is done in place and affects the original array. No copy is made. The default sort is in ascending string order. - -The `.sort()` method allows the passing of a comparison function to change the ordering of the sort. - -## Syntax - -```pseudo -// Perform the default sort -someArray.sort() - -// Perform the sort using an arrow function for comparisons -somearray.sort((A, B) => { ... } ) - -// Perform the sort with an inline compare function -somearray.sort(function compareFn(A, B) { ... }) - -// Perform the sort with a compare function -somearray.sort(compareFn) -``` - -- `compareFn` is the optional comparison function. -- `A` is the first array item being compared. -- `B` is the second array item being compared. - -## Default Sort Order - -If no comparison function are provided, the `.sort()` method will sort the array in ascending string order. - -For items that are not strings, `.sort()` will convert them into strings before comparing them. This can lead to unexpected results: - -```js -let numbers = [33, 16, 156, 2, 9, 5, 10]; - -numbers.sort(); - -console.log(numbers); -// Output: [10, 156, 16, 2, 33, 5, 9] -``` - -## Comparison Function - -The comparison function, if provided, will determine the sorting of all non-`undefined` items in the array. All `undefined` items are sorted to the end of the array, and no `undefined` items are passed to the comparison function. - -The comparison function determines the sort order as follows: - -For the function `CompareFn(A, B)`: - -- If the function returns a value greater than zero, sort `B` before `A`. -- If the function returns a value less than zero, sort `A` before `B`. -- If the function returns a value of zero, the positions of `A` and `B` remain unchanged. -- The function must return the same result for any specific pair of values `A` and `B` provided. Otherwise, the sort order is undefined. - -To sort an array in numeric order rather than string order, the following function can be used as long as the array doesn't contain `Infinity` or `NaN`: - -```js -function compareFn(A, B) { - return A - B; -} -``` - -So we can fix the prior example: - -```js -let numbers = [33, 16, 156, 2, 9, 5, 10]; - -numbers.sort(function compareFn(A, B) { - return A - B; -}); - -console.log(numbers); -// Output: [2, 5, 9, 10, 16, 33, 156] -``` - -## Codebyte Example - -The below Codebyte example uses a comparison function with `.sort()` in order to sort the array alphabetically while ignoring the case: - -```codebyte/javascript -//Comparison Function -function compareFn(A, B) { - if (A.toLowerCase() > B.toLowerCase()) { - return 1; - } - if (A.toLowerCase() < B.toLowerCase()) { - return -1; - } - return 0; -} - -let array = ["alpha","Beta", "gamma", "delta", "epsilon", "Zeta", "Eta", "theta"]; - -//The output without using the comparison function -console.log(array.sort()); - -//The output with using the comparison function -console.log(array.sort(compareFn)); -``` From e20e5147662775f18d5d36786522a90b2c87673e Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Mon, 15 Sep 2025 11:27:32 +0530 Subject: [PATCH 2/3] updated faqs 2 and 3 --- .../concepts/arrays/terms/sort/sort.md | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/content/javascript/concepts/arrays/terms/sort/sort.md b/content/javascript/concepts/arrays/terms/sort/sort.md index 9c694d016e5..d5ea23cee7c 100644 --- a/content/javascript/concepts/arrays/terms/sort/sort.md +++ b/content/javascript/concepts/arrays/terms/sort/sort.md @@ -39,9 +39,7 @@ This example uses JS `.sort()` to sort an array of strings: ```js const fruits = ['banana', 'apple', 'cherry', 'date']; - fruits.sort(); - console.log(fruits); ``` @@ -57,9 +55,7 @@ This example uses JS `.sort()` with a comparison function to sort an array of nu ```js const numbers = [10, 5, 20, 1, 100]; - numbers.sort((a, b) => a - b); - console.log(numbers); ``` @@ -95,14 +91,21 @@ You can reverse the comparison in your function in JS `.sort()` to sort numbers numbers.sort((a, b) => b - a); ``` -### 2. Does JS `.sort()` modify the original array? +### 2. Can I use `sort()` on a string? -Yes. JS `.sort()` performs in-place sorting, meaning the original array is modified instead of creating a new one. +No. The `sort()` method is only available on arrays, not on strings. If you want to sort the characters of a string, you first need to convert it into an array (for example, using `split()`), apply `sort()`, and then join it back: + +```js +const str = "hello"; +const sorted = str.split("").sort().join(""); +console.log(sorted); // "ehllo" +``` -### 3. Can I sort strings in reverse alphabetical order using JS `.sort()`? +### 3. What happens when `sort()` is used in a list (array)? -Yes, you can sort strings in reverse alphabetical order using JS `.sort()` with `.reverse()`: +When you call `sort()` on an array, JavaScript converts the elements to strings by default and compares them in Unicode code point order. This means that numbers may not sort as you expect: ```js -fruits.sort().reverse(); +const numbers = [10, 1, 5]; +console.log(numbers.sort()); // [1, 10, 5] (string comparison) ``` From 243751553777d490da72ccb40b5bc9982dc4f7d2 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Mon, 15 Sep 2025 16:52:33 +0530 Subject: [PATCH 3/3] fixed format --- content/javascript/concepts/arrays/terms/sort/sort.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/javascript/concepts/arrays/terms/sort/sort.md b/content/javascript/concepts/arrays/terms/sort/sort.md index d5ea23cee7c..9ccdac1a5a9 100644 --- a/content/javascript/concepts/arrays/terms/sort/sort.md +++ b/content/javascript/concepts/arrays/terms/sort/sort.md @@ -96,8 +96,8 @@ numbers.sort((a, b) => b - a); No. The `sort()` method is only available on arrays, not on strings. If you want to sort the characters of a string, you first need to convert it into an array (for example, using `split()`), apply `sort()`, and then join it back: ```js -const str = "hello"; -const sorted = str.split("").sort().join(""); +const str = 'hello'; +const sorted = str.split('').sort().join(''); console.log(sorted); // "ehllo" ```