Based on your recent update, it seems asr
is an array with properties you've added. That's not generally a good idea unless you know what you're doing, and sort()
won't touch those properties.
Instead, I would use a normal object, with the caveat that objects in JavaScript aren't really meant to contain an ordered collection of values. With that caveat out of the way, this is how I'd store the data, and how I'd sort the keys:
const asr = {by: 3, ds: 14, de: 2, vi: 1, sr: 2}
console.log(
Object.fromEntries(
Object.entries(asr).sort(
([ak, av], [bk, bv]) => av > bv ? 1 : -1
)
)
)
I'll keep the rest here, even though it isn't relevant to your question.
asr
is most likely an array of objects, in which case asr.sort()
has sorted the array by the result of the contained objects' toString
method:
const asr = [{vi: 1}, {sr: 2}, {by: 3}, {ds: 14}, {de: 2}]
console.log(asr.sort())
If you want to sort it by object values, this will do the trick:
const asr = [{vi: 1}, {sr: 2}, {by: 3}, {ds: 14}, {de: 2}]
console.log(asr.sort(
(a, b) => Object.values(a)[0] > Object.values(b)[0] ? 1 : -1
))
If you want to sort by object keys, this should work:
const asr = [{vi: 1}, {sr: 2}, {by: 3}, {ds: 14}, {de: 2}]
console.log(asr.sort(
(a, b) => Object.keys(a)[0] > Object.keys(b)[0] ? 1 : -1
))