// Price Low To High
array?.sort((a, b) => (a.price > b.price ? 1 : -1))
// Price High To Low
array?.sort((a, b) => (a.price > b.price ? -1 : 1))
// Name A to Z
array?.sort((a, b) => (a.name > b.name ? 1 : 1))
// Name Z to A
array?.sort((a, b) => (a.name > b.name ? -1 : 1))
// Sort by date
array.sort((a,b) => new Date(b.date) - new Date(a.date));
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.localeCompare(b.name))
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;
}
Sort and Reverse an array of Objects using JavaScript
<!DOCTYPE html>
<html>
<body>
<p>The reverse() method reverses the elements in an array.</p>
<p>By combining sort() and reverse() you can sort an array in descending order.</p>
<button onclick=”sortAndReverseArrayValue()”>Click</button>
<p id=”pId”></p>
<script>
var banksOfIndis = [“CentralBankOfIndia”,”AndhraBank”,”BankOfBaroda”,”CanaraBank”,”AllhabadBank”];
document.getElementById(“pId”).innerHTML = banksOfIndis;
function sortAndReverseArrayValue() {
banksOfIndis.sort();
banksOfIndis.reverse();
document.getElementById(“pId”).innerHTML = banksOfIndis;
}
</script>
</body>
</html>
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);