Home > database >  Sorting a array by its object value
Sorting a array by its object value

Time:05-18

I want to sort this array by its xp object:

[
  ["438449925949489153", {
    "xp": 2
  }],
  ["534152271443415140", {
    "xp": 3
  }],
  ["955210908794236938", {
    "xp": 1
  }]
]

So that it returns this array:

[
  ["955210908794236938", {
    "xp": 1
  }],
  ["438449925949489153", {
    "xp": 2
  }],
  ["534152271443415140", {
    "xp": 3
  }]
]

I've tried to do this with the sort-json npm module but it sorted the first value instead of xp

const sortJson = require('sort-json');
sortJson(array)

CodePudding user response:

You can just use the native sort:

let data = [
  ["438449925949489153", {
    "xp": 2
  }],
  ["955210908794236938", {
    "xp": 3
  }],
  ["955210908794236938", {
    "xp": 1
  }]
];

const ascending = (a,b) => a[1].xp - b[1].xp;
const descending = (a,b) => b[1].xp - a[1].xp;

data.sort(ascending);

console.log(data)

data.sort(descending);

console.log(data)

Notice that sort mutates the original array: if you don't want to do that, you need do perform a shallow copy of the original array.

CodePudding user response:

sort descending:

arr.sort((a,b) =>{
    if (a[1].xp < b[1].xp) return 1
    else return -1
})

sort ascending:

arr.sort((a,b) =>{
    if (a[1].xp < b[1].xp) return -1
    else return 1
})

CodePudding user response:

I would suggest a bit more clean implementation:

function compare( a, b ) {
  if ( a[1] < b[1]){
    return -1;
  }
  if ( a[1] > b[1] ){
    return 1;
  }
  return 0;
}
    
arr.sort( compare );

Or one-liner:

arr.sort((a,b) => (a[1] > b[1]) ? 1 : ((b[1] > a[1]) ? -1 : 0))
  • Related