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// function that returns a string in alphabetical order
2function reorderStr(str) {
3 return [...str].sort().join('');
4}
5console.log(reorderStr("hacker")); //"acehkr"
6console.log(reorderStr("javascript"));//"aacijprstv"
1const months = ['March', 'Jan', 'Feb', 'Dec'];
2months.sort();
3console.log(months);
4// expected output: Array ["Dec", "Feb", "Jan", "March"]
1var names = ["Peter", "Emma", "Jack", "Mia"];
2var sorted = names.sort(); // ["Emma", "Jack", "Mia", "Peter"]
1if (item1.attr < item2.attr)
2 return -1;
3if ( item1.attr > item2.attr)
4 return 1;
5return 0;