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);
numArray.sort((a, b) => b - a);
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];
});
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();