Skip to content Skip to sidebar Skip to footer

How To Sort Json Array Elements In Descending Order?

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, keyOn

Solution 1:

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.

Solution 2:

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

my_array.sort(function(a, b) {
    if (a.id > b.id) return -1;
    elseif (a.id < b.id) return1;
    elsereturn0;
});

Solution 3:

const JsonArray= [
    { 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 JsonReversedArray= JsonArray.reverse();

console.log(JsonReversedArray);

Reverse the order of the elements in an array of object

but this will not work in this case

const JsonArray= [
    { id: 1, keyOne: "valueOne", keyTwo: "valueTwo"},
    { id: 5, keyOne: "valueOne", keyTwo: "valueTwo"},
    { id: 3, keyOne: "valueOne", keyTwo: "valueTwo"},  
    { id: 4, keyOne: "valueOne", keyTwo: "valueTwo"}
];

as u see here the reverse method reverse your array if your id are already in order so :

letJsonReversedArray= JsonArray.sort((a,b) => b.id - a.id);

this one will be correct for this case

Post a Comment for "How To Sort Json Array Elements In Descending Order?"