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});
1Here’s the java program to sort an array using Arrays.sort() method.
2
3import java.util.Arrays;
4public class JavaArraySortMethod
5{
6 public static void main(String[] args)
7 {
8 String[] strGiven = {"Great Barrier Reef", "Paris", "borabora", "Florence","tokyo", "Cusco"};
9 Arrays.sort(strGiven);
10 System.out.println("Output(case sensitive) : " + Arrays.toString(strGiven));
11 }
12}
1const points = [40, 100, 1, 5, 25, 10];
2points.sort(function(a, b){return a - b}); // for ascending
3//another way for ascending
4points.sort((a,b)=>{
5 if(a>b){
6 return 1
7 }else if(a<b){
8 return -1
9 }else{
10 return 0
11 }
12})
13points.sort(function(a, b){return b - a}); // for descending
14//another way for descending
15points.sort((a,b)=>{
16 if(a>b){
17 return -1
18 }else if(a<b){
19 return 1
20 }else{
21 return 0
22 }
23})
24
1import java.util.Scanner;
2public class JavaExample
3{
4 public static void main(String[] args)
5 {
6 int count, temp;
7
8 //User inputs the array size
9 Scanner scan = new Scanner(System.in);
10 System.out.print("Enter number of elements you want in the array: ");
11 count = scan.nextInt();
12
13 int num[] = new int[count];
14 System.out.println("Enter array elements:");
15 for (int i = 0; i < count; i++)
16 {
17 num[i] = scan.nextInt();
18 }
19 scan.close();
20 for (int i = 0; i < count; i++)
21 {
22 for (int j = i + 1; j < count; j++) {
23 if (num[i] > num[j])
24 {
25 temp = num[i];
26 num[i] = num[j];
27 num[j] = temp;
28 }
29 }
30 }
31 System.out.print("Array Elements in Ascending Order: ");
32 for (int i = 0; i < count - 1; i++)
33 {
34 System.out.print(num[i] + ", ");
35 }
36 System.out.print(num[count - 1]);
37 }
38}
1var carBrands = ["Toyota", "Jeep", "Ford", "Volvo"];
2carBrands.sort();
3// array.sort() method sorts an array in ascending order by default
4// extend the function like below to sort in descending order or customize
5//carBrands.sort(function(a, b){return b-a});