JAVASCRIPT BASIC
JAVASCRIPT & DOM
JAVASCRIPT & BOM
JAVASCRIPT ADVANCED
JAVASCRIPT EXAMPLES
JAVASCRIPT REFERENCE
Advertisements

JavaScript Sorting Arrays

In this tutorial you will learn how to sort array elements in JavaScript.

Sorting an Array

Sorting is a common task when working with arrays. It would be used, for instance, if you want to display the city or county names in alphabetical order.

The JavaScript Array object has a built-in method sort() for sorting array elements in alphabetical order. The following example demonstrates how it works:

let fruits = ["Banana", "Orange", "Apple", "Papaya", "Mango"];
let sorted = fruits.sort();

alert(fruits); // Outputs: Apple,Banana,Mango,Orange,Papaya
alert(sorted); // Outputs: Apple,Banana,Mango,Orange,Papaya

Reversing an Array

You can use the reverse() method to reverse the order of the elements of an array.

This method reverses an array in such a way that the first array element becomes the last, and the last array element becomes the first. Here's an example:

let counts = ["one", "two", "three", "four", "five"];
let reversed = counts.reverse(); 

alert(counts); // Outputs: five,four,three,two,one
alert(reversed); // Output: five,four,three,two,one

Note: The sort() and reverse() method modifies the original array and return a reference to the same array, as you can see in the above examples.


Sorting Numeric Arrays

The sort() method may produce unexpected result when it is applied on the numeric arrays (i.e. arrays containing numeric values). For instance:

let numbers = [5, 20, 10, 75, 50, 100];
numbers.sort(); // Sorts numbers array
alert(numbers); // Outputs: 10,100,20,5,50,75

As you can see, the result is different from what we've expected. It happens because, the sort() method sorts the numeric array elements by converting them to strings (i.e. 20 becomes "20", 100 becomes "100", and so on), and since the first character of string "20" (i.e. "2") comes after the first character of string "100" (i.e. "1"), that's why the value 20 is sorted after the 100.

To fix this sorting problem with numeric array, you can pass a compare function, like this:

let numbers = [5, 20, 10, 75, 50, 100];

// Sorting an array using compare function
numbers.sort(function(a, b) {
    return a - b;
});
alert(numbers); // Outputs: 5,10,20,50,75,100

As you can see, this time we've got the correct result. Let's see how it works.

When compare function is specified, array elements are sorted according to the return value of the compare function. For example, when comparing a and b:

  • If the compare function returns a value less than 0, then a comes first.
  • If the compare function returns a value greater than 0, then b comes first.
  • If the compare function returns 0, a and b remain unchanged with respect to each other, but sorted with respect to all other elements.

Hence, since 5 - 20 = -15 which is less than 0, therefore 5 comes first, similarly 20 - 10 = 10 which is greater than 0, therefore 10 comes before 20, likewise 20 - 75 = -55 which is less than 0, so 20 comes before 75, similarly 50 comes before 75, and so on.


Finding the Maximum and Minimum Value in an Array

You can use the apply() method in combination with the Math.max() and Math.min() to find the maximum and minimum value inside an array, like this:

let numbers = [3, -7, 10, 8, 15, 2];

// Defining function to find maximum value
function findMax(array) {
    return Math.max.apply(null, array);
}

// Defining function to find minimum value
function findMin(array) {
    return Math.min.apply(null, array);
}

alert(findMax(numbers)); // Outputs: 15
alert(findMin(numbers)); // Outputs: -7

The apply() method provides a convenient way to pass array values as arguments to a function that accepts multiple arguments in an array-like manner, but not an array (e.g. Math.max() and Math.min() methods here). So, the resulting statement Math.max.apply(null, numbers) in the example above is equivalent to the Math.max(3, -7, 10, 8, 15, 2).


Sorting an Array of Objects

The sort() method can also be used for sorting object arrays using the compare function.

The following example will show you how to sort an array of objects by property values:

let persons = [
    { name: "Harry", age: 14 },
    { name: "Ethan", age: 30 },
    { name: "Peter", age: 21 },
    { name: "Clark", age: 42 },
    { name: "Alice", age: 16 }
];

// Sort by age
persons.sort(function (a, b) {
    return a.age - b.age;
});

console.log(persons);

// Sort by name
persons.sort(function(a, b) {
    let x = a.name.toLowerCase(); // ignore upper and lowercase
    let y = b.name.toLowerCase(); // ignore upper and lowercase
    if(x < y) {
        return -1;
    }
    if(x > y) {
        return 1;
    }
    // names must be equal
    return 0;
});

console.log(persons);
Advertisements
Bootstrap UI Design Templates