1const books = [
2 {id: 1, name: 'The Lord of the Rings'},
3 {id: 2, name: 'A Tale of Two Cities'},
4 {id: 3, name: 'Don Quixote'},
5 {id: 4, name: 'The Hobbit'}
6]
7
8books.sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));
1var array = [
2 {name: "John", age: 34},
3 {name: "Peter", age: 54},
4 {name: "Jake", age: 25}
5];
6
7array.sort(function(a, b) {
8 return a.age - b.age;
9}); // Sort youngest first
1const list = [
2 { color: 'white', size: 'XXL' },
3 { color: 'red', size: 'XL' },
4 { color: 'black', size: 'M' }
5]
6
7var sortedArray = list.sort((a, b) => (a.color > b.color) ? 1 : -1)
8
9// Result:
10//sortedArray:
11//{ color: 'black', size: 'M' }
12//{ color: 'red', size: 'XL' }
13//{ color: 'white', size: 'XXL' }
1const books = [
2 {id: 1, name: 'The Lord of the Rings'},
3 {id: 2, name: 'A Tale of Two Cities'},
4 {id: 3, name: 'Don Quixote'},
5 {id: 4, name: 'The Hobbit'}
6]
7
8books.sort((a, b) => a.name.localeCompare(b.name))
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});