The Array.sort() function can be used to sort an array of objects by key value. This can be useful when you need to sort an array of objects by a certain criteria, such as alphabetical order or numerical value.
Sort in ascending order - by score value
const subjects = [
{ "name": "Math", "score": 81 },
{ "name": "English", "score": 77 },
{ "name": "Chemistry", "score": 87 },
{ "name": "Physics", "score": 84 }
];
// Sort in ascending order - by score
subjects.sort( (a,b) => a.score - b.score );
console.log(subjects);
or you can also write it as below:
subjects.sort((a, b) => (a.score > b.score) ? 1: -1);
Output
[
{"name":"English","score":77},
{"name":"Math","score":81},
{"name":"Physics","score":84},
{"name":"Chemistry","score":87}
]
This code is sorting the array called subjects in ascending order by the score property using Array.sort() function.
Sort in descending order - by score value
const subjects = [
{ "name": "Math", "score": 81 },
{ "name": "English", "score": 77 },
{ "name": "Chemistry", "score": 87 },
{ "name": "Physics", "score": 84 }
];
// Sort in descending order - by score
subjects.sort((a, b) => b.score - a.score);
console.log(subjects);
Or
subjects.sort((a, b) => (a.score < b.score) ? 1: -1);
Output
[
{"name":"Chemistry","score":87},
{"name":"Physics","score":84},
{"name":"Math","score":81},
{"name":"English","score":77}
]
This is an example of how to sort an array of objects in JavaScript in descending order by score.
The code defines an array of objects, each with a name and score property.
The code then sorts the array in descending order by score and logs the sorted array to the console.
Sort in ascending order by name 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);
Output
[
{"name":"Chemistry","score":87},
{"name":"English","score":77},
{"name":"Math","score":81},
{"name":"Physics","score":84}
]
Sort array of objects in descending order by name value
const subjects = [
{ "name": "Math", "score": 81 },
{ "name": "English", "score": 77 },
{ "name": "Chemistry", "score": 87 },
{ "name": "Physics", "score": 84 }
];
// Sort in descending order - by name
subjects.sort((a, b) => (a.name < b.name) ? 1 : -1);
console.log(subjects);
Output
[
{"name":"Physics","score":84},
{"name":"Math","score":81},
{"name":"English","score":77},
{"name":"Chemistry","score":87}
]
0 Comments