-1

I have array obj like this:

[{ A: '24/12/2020', J: 54106, }, { A: '10/dd/2020', J: 54103 }, { A: 'mm/29/2020', J: 54103 }]

I wanna sort J field first then sort A field .. but I have issue when I sort, I wanna result like this :

[ { A: '10/dd/2020', J: 54103 }, { A: 'mm/29/2020', J: 54103 }, { A: '24/12/2020', J: 54106, }]

but data response is :

[{ A: 'mm/29/2020', J: 54103 }, { A: '10/dd/2020', J: 54103 }, { A: '24/12/2020', J: 54106, }]

My code here :

result.sort(function (a, b) {
  return parseFloat(a.J) - parseFloat(b.J) || (a.A) - (b.A);
});

I think it need sort from number to text but it's not like that

2
  • parentheses around a single value have no effect. Commented Nov 2, 2020 at 11:18
  • what is thew wanted order of the part date string? Commented Nov 2, 2020 at 12:06

1 Answer 1

2

Just write a compare function to sort it. First compare the J fields and then compare the A fields.

const data = [
  { A: '24/12/2020', J: 54106 },
  { A: '10/dd/2020', J: 54103 },
  { A: 'mm/29/2020', J: 54103 },
];

const cmp = (x, y) => {
  if (x.J === y.J) {
    return x.A.localeCompare(y.A);
  }
  return x.J > y.J ? 1 : -1;
};
const ret = data.sort(cmp);
console.log(ret);

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

7 Comments

I don't know why but it's not working when "A": "mm/29/2020" is in first obj, check it: link
What is A field? Do you want to compare it as a date or string?
I just want to compare as string, I think number will be sort first then character, it's right?
I try with this data but not working too: const data = [ { A: 'mm', J: 54103, }, { A: '10', J: 54103, } ];
now check it and let me know it's working or not.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.