javascript sort array with objects
var array = [
{name: "John", age: 34},
{name: "Peter", age: 54},
{name: "Jake", age: 25}
];
array.sort(function(a, b) {
return a.age - b.age;
}); // Sort youngest first
javascript sort array with objects
var array = [
{name: "John", age: 34},
{name: "Peter", age: 54},
{name: "Jake", age: 25}
];
array.sort(function(a, b) {
return a.age - b.age;
}); // Sort youngest first
sorting array from highest to lowest javascript
// Sort an array of numbers
let numbers = [5, 13, 1, 44, 32, 15, 500]
// Lowest to highest
let lowestToHighest = numbers.sort((a, b) => a - b);
//Output: [1,5,13,15,32,44,500]
//Highest to lowest
let highestToLowest = numbers.sort((a, b) => b-a);
//Output: [500,44,32,15,13,5,1]
how to sort an array by value in javascript
//ascending order
arr.sort(function(a, b){return a-b});
arr.sort((a, b) => a - b);
//descending order
arr.sort(function(a, b){return b - a});
arr.sort((a, b) => b - a);
sort array of objects by string property value
function compareFirstNames( a, b ) {
if ( a.first_name < b.first_name ){
return -1;
}
if ( a.first_name > b.first_name ){
return 1;
}
return 0;
}
var people =[
{"first_name":"Carol", "age":29},
{"first_name":"Anna", "age":32},
{"first_name":"Bob", "age":32}
];
people.sort( compareFirstNames ); //people is now sorted by first name from a-z
javascript sort
var names = ["Peter", "Emma", "Jack", "Mia", "Eric"];
names.sort(); // ["Emma", "Eric", "Jack", "Mia", "Peter"]
var objs = [
{name: "Peter", age: 35},
{name: "Emma", age: 21},
{name: "Jack", age: 53}
];
objs.sort(function(a, b) {
return a.age - b.age;
}); // Sort by age (lowest first)
javascript sort
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us