1numArray.sort((a, b) => a - b); // For ascending sort
2numArray.sort((a, b) => b - a); // For descending sort
3
1var items = [
2 { name: 'Edward', value: 21 },
3 { name: 'Sharpe', value: 37 },
4 { name: 'And', value: 45 },
5 { name: 'The', value: -12 },
6 { name: 'Magnetic', value: 13 },
7 { name: 'Zeros', value: 37 }
8];
9
10// sort by value
11items.sort(function (a, b) {
12 return a.value - b.value;
13});
14
15// sort by name
16items.sort(function(a, b) {
17 var nameA = a.name.toUpperCase(); // ignore upper and lowercase
18 var nameB = b.name.toUpperCase(); // ignore upper and lowercase
19 if (nameA < nameB) {
20 return -1;
21 }
22 if (nameA > nameB) {
23 return 1;
24 }
25
26 // names must be equal
27 return 0;
28});
1
2
3
4
5 let numbers = [0, 1, 2, 3, 10, 20, 30];
6numbers.sort((a, b) => a - b);
7
8console.log(numbers);
1var test = ['b', 'c', 'd', 'a'];
2var len = test.length;
3var indices = new Array(len);
4for (var i = 0; i < len; ++i) indices[i] = i;
5indices.sort(function (a, b) { return test[a] < test[b] ? -1 : test[a] > test[b] ? 1 : 0; });
6console.log(indices);
1numArray.sort((a, b) => a - b); // For ascending sort
2numArray.sort((a, b) => b - a); // For descending sort
1arr = ['width', 'score', done', 'neither' ]
2arr.sort() // results to ["done", "neither", "score", "width"]
3
4arr.sort((a,b) => a.localeCompare(b))
5// if a-b (based on their unicode values) produces a negative value,
6// a comes before b, the reverse if positive, and as is if zero
7
8//When you sort an array with .sort(), it assumes that you are sorting strings
9//. When sorting numbers, the default behavior will not sort them properly.
10arr = [21, 7, 5.6, 102, 79]
11arr.sort((a, b) => a - b) // results to [5.6, 7, 21, 79, 102]
12// b - a will give you the reverse order of the sorted items
13
14//this explnation in not mine