es-toolkit icon indicating copy to clipboard operation
es-toolkit copied to clipboard

feat(orderBy): add handling one is a string and the other is a number case

Open dayongkr opened this issue 1 year ago • 2 comments

Description

If value a is a 'hello' and value b is a 24, then value a will be converted to NaN. So, a > b and a < b will be false in this case.

Because Javascript converts to number, when types of the compared values are not same.

So in this update, I enhanced the compareValues function to handle cases where the types of a and b differ between strings and numbers.

Handling the other cases like object or array type is not good for our simplicity, So I just return 0 in these cases.

The function now converts number to string when necessary to ensure they can be compared correctly without causing NaN errors.

Specifically, if a is a string and b is a number (or vice versa), the number is converted to a string before comparison.

This adjustment prevents issues that might arise when comparing mixed types and ensures consistent behavior when sorting or ordering data.

If this enhancement is acceptable, then I will add this description in a document.

Example

const data = [
  { id: 1, value: 'a' },
  { id: 2, value: 2 },
  { id: 12, value: 1 },
  { id: 5, value: 'b' },
  { id: 4, value: 2 },
  { id: 43, value: 'c' },
  { id: 24, value: 3 },
  { id: 3, value: '3a' },
  { id: 6, value: '2a' },
  { id: 7, value: '1cs' },
];

console.log(orderBy(data, ['value', 'id'], ['asc', 'asc']))
/*
[
  { id: 12, value: 1 },
  { id: 7, value: '1cs' },
  { id: 2, value: 2 },
  { id: 4, value: 2 },
  { id: 6, value: '2a' },
  { id: 24, value: 3 },
  { id: 3, value: '3a' },
  { id: 1, value: 'a' },
  { id: 5, value: 'b' },
  { id: 43, value: 'c' },
]
*/

close #361

dayongkr avatar Aug 09 '24 10:08 dayongkr