Run

Tutorial With Example

Run your live code

 
​x
 
1
<html>
2
<head></head>
3
<body>
4
  <script>
5
   var persons = [
6
      { name: "Harry", age: 14 },
7
      { name: "Ethan", age: 30 },
8
      { name: "Peter", age: 21 },
9
      { name: "Clark", age: 42 },
10
      { name: "Alice", age: 16 }
11
    ];
12
​
13
    // Sort by age
14
    persons.sort(function (a, b) {
15
        return a.age - b.age;
16
    });
17
​
18
    console.log(persons);
19
​
20
    // Sort by name
21
    persons.sort(function(a, b) {
22
        var x = a.name.toLowerCase(); // ignore upper and lowercase
23
        var y = b.name.toLowerCase(); // ignore upper and lowercase
24
        if(x < y) {
25
            return -1;
26
        }
27
        if(x > y) {
28
            return 1;
29
        }
30
        // names must be equal
31
        return 0;
32
    });
33
​
34
    console.log(persons);
35
  </script>
36
</body>
37
</html>