3

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?

1
  • What did you try that didn't work? Commented Jan 11, 2019 at 18:16

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that sorts also happen "in place," so the input variable will get modified as well. See mdn - sort for more details.
Thanks for feedback, updated to don't touch the original input. Anyway, he don't say anything about not mutating the input.
0

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;
    else if (a.id < b.id) return 1;
    else return 0;
});

Comments

0
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 :

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

this one will be correct for this case

Comments