0

I am trying to sort the following array based on the num in javascript

[ { name: 'sample',
    info: '{"num":10,"type":"detox"}',
    hex: 'bdafa7' },
  { name: 'sample',
    info: '{"num":5,"type":"detox"}',
    hex: 'bdafaj' },
  { name: 'sample',
    info: '{"num":0,"type":"detox"}',
    hex: 'bdafah' },
  { name: 'sample',
    info: '{"num":1,"type":"detox"}',
    hex: 'bdafay' }]

How can I achieve this

1
  • Hello! What have you tried so far? Commented Oct 11, 2018 at 23:20

1 Answer 1

1

Use a combination of Array.sort and JSON.parse:

let v = [ { name: 'sample',
    info: '{"num":10,"type":"detox"}',
    hex: 'bdafa7' },
  { name: 'sample',
    info: '{"num":5,"type":"detox"}',
    hex: 'bdafaj' },
  { name: 'sample',
    info: '{"num":0,"type":"detox"}',
    hex: 'bdafah' },
  { name: 'sample',
    info: '{"num":1,"type":"detox"}',
    hex: 'bdafay' }];

v.sort((a, b) => {
  return JSON.parse(a.info).num - JSON.parse(b.info).num
});

Returns

[
  {name: "sample", info: "{"num":10,"type":"detox"}", hex: "bdafa7"},
  {name: "sample", info: "{"num":5,"type":"detox"}", hex: "bdafaj"},
  {name: "sample", info: "{"num":1,"type":"detox"}", hex: "bdafay"},
  {name: "sample", info: "{"num":0,"type":"detox"}", hex: "bdafah"}
]
Sign up to request clarification or add additional context in comments.

3 Comments

The sort callback should return a number, not a boolean. JSON.parse(a.info).num - JSON.parse(b.info).num (- instead of <).
I wonder how many times I've made that mistake... Thanks Felix Kling.
That is wonderful !! I was not thinking in this direction that i should have used both array.sort and json.parse.

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.