How to sort JSON array elements in descending order?
This is easy to do using the sort() method of arrays:
const input = [
{id: 1, keyOne: "valueOne", keyTwo: "valueTwo"},
{id: 2, keyOne: "valueOne", keyTwo: "valueTwo"},
{id: 3, keyOne: "valueOne", keyTwo: "valueTwo"},
{id: 4, keyOne: "valueOne", keyTwo: "valueTwo"}
];
let sortedInput = input.slice().sort((a, b) => b.id - a.id);
console.log(sortedInput);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Note the usage of the slice() method, invoking slice()
is equals to invoke slice(0)
to make a shallow copy of the original array. This way, when sort()
is invoked it won't mutates the oiriginal input
array.
![Shidersz](https://i.stack.imgur.com/pRi10.png?s=256&g=1)
Shidersz
A developer with knowledges in the following areas: Web applications and systems with PHP, MySQL, Javascript / JQuery and CSS. Frameworks / libraries like: Laravel, AdminLTE and Bootstrap. Some of my answers: Javascript: Number (integer or decimal) to array, array to number (integer or decimal) without using strings How can I replace text dynamically time after time Is there a better way to extract information from a string? Insert new element after each nt-h array elements Generic formula for build an array of numbers of base-n Get Array of All Possible l33t Combinations in Javascript JQuery Datatables: Customization of Display Format for Datatables Plugin in Boostrap 3 MySQL: Subtract days from a date ignoring weekend days
Updated on June 28, 2022Comments
-
Shidersz about 2 years
In my index.html, I receive data from server which is in this order:
[ {id: 1, keyOne: valueOne, keyTwo: valueTwo}, {id: 2, keyOne: valueOne, keyTwo: valueTwo}, {id: 3, keyOne: valueOne, keyTwo: valueTwo}, {id: 4, keyOne: valueOne, keyTwo: valueTwo} ]
I want to sort this in descending order, like:
[ {id: 4, keyOne: valueOne, keyTwo: valueTwo}, {id: 3, keyOne: valueOne, keyTwo: valueTwo}, {id: 2, keyOne: valueOne, keyTwo: valueTwo}, {id: 1, keyOne: valueOne, keyTwo: valueTwo} ]
I have tried a number of ways from Stackoverflow but couldn't find a perfect match. How can I do this?
-
wlh over 5 yearsWhat did you try that didn't work?
-
-
romellem over 5 yearsNote that sorts also happen "in place," so the
input
variable will get modified as well. See mdn - sort for more details. -
Shidersz over 5 yearsThanks for feedback, updated to don't touch the original input. Anyway, he don't say anything about not mutating the input.