xxxxxxxxxx
<h2>JavaScript Array Sort</h2>
<p>Click the buttons to sort car objects on type.</p>
<button onclick="myFunction()">Sort</button>
<p id="demo"></p>
<script>
const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
displayCars();
function myFunction() {
cars.sort(function(a, b){
let x = a.type.toLowerCase();
let y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
displayCars();
}
function displayCars() {
document.getElementById("demo").innerHTML =
cars[0].type + " " + cars[0].year + "<br>" +
cars[1].type + " " + cars[1].year + "<br>" +
cars[2].type + " " + cars[2].year;
}
</script>
xxxxxxxxxx
const books = [
{id: 1, name: 'The Lord of the Rings'},
{id: 2, name: 'A Tale of Two Cities'},
{id: 3, name: 'Don Quixote'},
{id: 4, name: 'The Hobbit'}
]
books.sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));
xxxxxxxxxx
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]]
xxxxxxxxxx
function sortObjectByValue(obj) {
const entries = Object.entries(obj);
entries.sort((a, b) => a[1] - b[1]);
const sortedObject = Object.fromEntries(entries);
return sortedObject;
}
// Example usage:
const unsortedObject = {
apples: 3,
bananas: 1,
oranges: 2,
};
const sortedObject = sortObjectByValue(unsortedObject);
console.log(sortedObject);
xxxxxxxxxx
let persolize=[ { key: 'speakers', view: 10 }, { key: 'test', view: 5 } ]
persolize.sort((a,b) => a.view - b.view);
//If it only array and not an array object, use below statement
//persolize.sort((a,b) => a - b);
xxxxxxxxxx
//using es6, simply:
data.sort((a, b) => a.city.localeCompare(b.city) || b.price - a.price);
xxxxxxxxxx
const sortObject = (object) => {
const sortedObject = Object.fromEntries(Object.entries(object).sort((a, b) => b[1] - a[1]));
return sortedObject
}
xxxxxxxxxx
list.sort((a, b) => (a.color > b.color) ? 1 : (a.color === b.color) ? ((a.size > b.size) ? 1 : -1) : -1 )
xxxxxxxxxx
var maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
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]]
xxxxxxxxxx
function compareFn(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}