-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

1 Answers1

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);
mr hr
  • 3,162
  • 2
  • 9
  • 19