how to sort js array code example

Example 1: sort javascript array

var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)

Example 2: sort js

numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort

Example 3: javascript sort object

var maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 28800
};
var sortable = [];
for (var vehicle in maxSpeed) {
    sortable.push([vehicle, maxSpeed[vehicle]]);
}

sortable.sort(function(a, b) {
    return a[1] - b[1];
});

//[["bike", 60], ["motorbike", 200], ["car", 300],
//["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

Example 4: javascript sort

homes.sort(function(a, b) {
    return parseFloat(a.price) - parseFloat(b.price);
});

Example 5: put array in alphabetical order

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

Tags:

Php Example