Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript sort array of objects by number

// 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));
Comment

sort array of objects javascript by value

const subjects = [
    { "name": "Math", "score": 81 },
    { "name": "English", "score": 77 },
    { "name": "Chemistry", "score": 87 },
    { "name": "Physics", "score": 84 }
];

// Sort in ascending order - by name
subjects.sort((a, b) => (a.name > b.name) ? 1: -1);

console.log(subjects);
Comment

Sorting Array of String, Numbers or Objects in javascript

const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// Output
(4) ["Joe", "Kapil", "Musk", "Steve"]

stringArr.reverse();
// Output
(4) ["Steve", "Musk", "Kapil", "Joe"]

### Sort Number Array in javascript
const array  = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// Output
(6) [1, 5, 10, 25, 40, 100]

array.sort((a,b) => b-a);
// Output
(6) [100, 40, 25, 10, 5, 1]
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript random boolean 
Javascript :: wordpress header script add 
Javascript :: concurrently node react 
Javascript :: how to let a function execute after 5 seconds javascript 
Javascript :: js string replaceall 
Javascript :: writing to file in node js 
Javascript :: sequelize generate migration 
Javascript :: trheejs cube mesh 
Javascript :: jacksepticeye 
Javascript :: mongoose timestamps 
Javascript :: javascript get highlighted text 
Javascript :: regx get only domain name from url 
Javascript :: javascript get domain name from string 
Javascript :: javascript add div before element 
Javascript :: field options mongoose 
Javascript :: javascript group array by key 
Javascript :: react map array limit 
Javascript :: reactjs checkbox 
Javascript :: javascript middle of array 
Javascript :: js get paste text 
Javascript :: scroll to top jquery 
Javascript :: prime factorization javascript 
Javascript :: how to set height dynamically in jquery 
Javascript :: array to dictionary javascript 
Javascript :: window onload javascript 
Javascript :: translatex in javascript 
Javascript :: read json file node js 
Javascript :: nombre random js 
Javascript :: angular form set value without fire event 
Javascript :: js reduce concat numbers 
ADD CONTENT
Topic
Content
Source link
Name
2+3 =