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?

Shidersz
  • 16,846
  • 2
  • 23
  • 48

3 Answers3

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.

Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • 1
    Note that sorts also happen "in place," so the `input` variable will get modified as well. See [mdn - sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) for more details. – romellem Jan 11 '19 at 18:19
  • Thanks for feedback, updated to don't touch the original input. Anyway, he don't say anything about not mutating the input. – Shidersz Jan 11 '19 at 18:22
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;
});
romellem
  • 5,792
  • 1
  • 32
  • 64
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

Aziz.G
  • 3,599
  • 2
  • 17
  • 35