0

Have got a JSON node as follows [{"a":1,"b":2,"c":1,"d":3,"e":2}] . Need to sort based on value not key in descending order.

Expected output [{"d":3,"e":2,"b":2,"c":1,"a":1}]

suhas
  • 733
  • 5
  • 13

1 Answers1

4

This would require a couple of helper functions (or a library like lodash):

let toPairs = s => Object.keys(s).map(k => [k, s[k]]);
let fromPairs = a => a.reduce((s, [k, v]) => Object.assign(s, {[k]: v}), {});
let cmp = (a, b) => (a > b) - (a < b);

a = {"a": 1, "b": 2, "c": 1, "d": 3, "e": 2};
b = fromPairs(
    toPairs(a).sort((x, y) =>
        cmp(y[1], x[1]) || cmp(y[0], x[0])))

console.log(b);

That said, it's usually unwise to rely on object properties being ordered in a particular way.

georg
  • 211,518
  • 52
  • 313
  • 390