You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Description: 'Returns an array with its items sorted in place.'
3
+
Description: 'Sorts the elements of an array in place.'
4
4
Subjects:
5
-
- 'Web Development'
6
5
- 'Computer Science'
6
+
- 'Web Development'
7
7
Tags:
8
8
- 'Arrays'
9
-
- 'Comparison'
10
9
- 'Functions'
11
10
- 'Methods'
12
-
- 'Sort'
13
-
- 'Unicode'
11
+
- 'Values'
14
12
CatalogContent:
15
13
- 'introduction-to-javascript'
16
14
- 'paths/front-end-engineer-career-path'
17
15
---
18
16
19
-
The **`.sort()`** method returns an array with its items sorted in place.
17
+
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.
20
18
21
-
## Syntax
19
+
## JS `.sort()`Syntax
22
20
23
21
```pseudo
24
-
// No parameters
25
-
array.sort();
26
-
27
-
// With optional function
28
-
array.sort((firstElement, secondElement) => { /* function body */ };
22
+
arr.sort(compareFn)
29
23
```
30
24
31
-
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).
25
+
**Parameters:**
32
26
33
-
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 */`.
27
+
-`compareFn` (Optional): A function that defines the sort order. It takes two arguments, `a` and `b`, and should return:
28
+
- A negative value if `a` should come before `b`
29
+
-`0` if `a` and `b` are considered equal
30
+
- A positive value if `a` should come after `b`
34
31
35
-
## Example
32
+
**Return value:**
36
33
37
-
In the following example, the `.sort()`method is applied to two arrays, `letters` and `numbers` (a mix of floats and integers):
34
+
JS `.sort()`returns the original array with its elements sorted in the given order.
38
35
39
-
```js
40
-
constletters= ['d', 'b', 'e', 'a', 'c'];
41
-
constnumbers= [5, 2, 123, 5.01, 43.5];
36
+
## Example 1: Sorting Array of Strings Using JS `.sort()`
42
37
43
-
console.log('Letters: ', letters.sort());
44
-
console.log('Numbers: ', numbers.sort());
38
+
This example uses JS `.sort()` to sort an array of strings:
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.
52
+
## Example 2: Sorting Array of Numbers Using JS `.sort()`
55
53
56
-
## Codebyte Example
54
+
This example uses JS `.sort()` with a comparison function to sort an array of numbers:
57
55
58
-
The following example showcases how the optional `callback` argument can be used to sort a `numbers` array in ascending and descending order:
56
+
```js
57
+
constnumbers= [10, 5, 20, 1, 100];
58
+
numbers.sort((a, b) => a - b);
59
+
console.log(numbers);
60
+
```
61
+
62
+
Here is the output:
63
+
64
+
```shell
65
+
[ 1, 5, 10, 20, 100 ]
66
+
```
67
+
68
+
## Codebyte Example: Sorting Array of Objects Using JS `.sort()`
69
+
70
+
This codebyte example uses JS `.sort()` to sort an array of objects:
59
71
60
72
```codebyte/javascript
61
-
const numbers = [5, 2, 123, 5.01, 43.5];
73
+
const users = [
74
+
{ name: "Alice", age: 25 },
75
+
{ name: "Bob", age: 20 },
76
+
{ name: "Charlie", age: 30 }
77
+
];
78
+
79
+
users.sort((a, b) => a.age - b.age);
62
80
63
-
const ascending = numbers.sort((a, b) => a - b);
64
-
console.log("Ascending order: ", ascending);
81
+
console.log(users);
82
+
```
83
+
84
+
## Frequently Asked Questions
85
+
86
+
### 1. How do I sort numbers in descending order using JS `.sort()`?
87
+
88
+
You can reverse the comparison in your function in JS `.sort()` to sort numbers in descending order:
89
+
90
+
```js
91
+
numbers.sort((a, b) => b - a);
92
+
```
93
+
94
+
### 2. Can I use `sort()` on a string?
65
95
66
-
const descending = numbers.sort((a, b) => b - a);
67
-
console.log("Descending order: ", descending);
96
+
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:
97
+
98
+
```js
99
+
conststr='hello';
100
+
constsorted=str.split('').sort().join('');
101
+
console.log(sorted); // "ehllo"
102
+
```
103
+
104
+
### 3. What happens when `sort()` is used in a list (array)?
105
+
106
+
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:
Copy file name to clipboardExpand all lines: content/pytorch/concepts/tensors/terms/randn/randn.md
+85-16Lines changed: 85 additions & 16 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -5,45 +5,114 @@ Subjects:
5
5
- 'Data Science'
6
6
- 'Machine Learning'
7
7
Tags:
8
+
- 'Python'
8
9
- 'PyTorch'
9
10
- 'Tensors'
11
+
- 'Values'
10
12
CatalogContent:
11
13
- 'intro-to-py-torch-and-neural-networks'
12
14
- 'py-torch-for-classification'
13
15
---
14
16
15
-
The **`.randn()`** function in PyTorch generates a tensor with random numbers drawn from a normal distribution with a mean of _0_ and a standard deviation of _1_. This function is particularly useful for initializing weights in neural networks and for other purposes requiring randomized data, especially in machine learning applications.
17
+
The **`torch.randn()`** function in PyTorch generates a [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors) with random numbers drawn from a standard normal distribution (mean = 0, variance = 1). This function is particularly useful for initializing weights in [neural networks](https://www.codecademy.com/resources/docs/ai/neural-networks) and for other purposes requiring randomized data, especially in machine learning applications.
`torch.randn()` creates a tensor containing random numbers drawn from a normal distribution.
110
+
111
+
### 2. What is the difference between `torch.rand()` and `torch.randn()`?
112
+
113
+
-`torch.rand()` generates numbers evenly spread between `0` and `1`.
114
+
-`torch.randn()` generates numbers based on the bell curve, centered at `0` with most values falling between `-3` and `3`.
115
+
116
+
### 3. What is the range of `torch.randn()`?
117
+
118
+
Theoretically, values for `torch.randn()` range from negative infinity to positive infinity because of the normal distribution. However, in practice, most values are between `-3` and `3`.
0 commit comments