0

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)
2
  • 2
    How is that result sorted? The greatest xp value among those three is 125124? Commented May 17, 2022 at 18:02
  • sort-json sorts by keys and not values ... The expected result above does not look sorted by keys either ... Commented May 17, 2022 at 18:05

3 Answers 3

2

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.

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

Comments

0

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
})

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.