Problem Description:
I’m encountering an issue where numeric values are being compared as strings, leading to incorrect results. Here’s the specific scenario:
When comparing values like 99 and 998 using string comparison logic, the expression 99 > 998 evaluates to true because JavaScript compares strings lexicographically (character by character). This is problematic in my sorting logic, which currently uses string comparison instead of numeric comparison.
Current Code Snippet:
javascript
fieldName = 'interact_info.liked_count';
if (a.json[fieldName] < b.json[fieldName]) {
return -1;
}
if (a.json[fieldName] > b.json[fieldName]) {
return 1;
}
return 0;
The Issue:
- The code treats values like
a.json[fieldName]andb.json[fieldName]as strings, causing incorrect comparisons (e.g.,'99' > '998'istrue). - I need to compare these values as actual numbers to ensure logical sorting (e.g.,
99 < 998).
What I’ve Tried:
I attempted to convert the values to numbers using Number(a.json[fieldName]), but the issue persists. I suspect there might be edge cases like null values, non-numeric strings, or formatted numbers (e.g., '1,234' or '¥99') that aren’t being handled correctly.
Expected Behavior:
- Values should be compared numerically, so
99is correctly identified as less than998. - The sorting logic should handle various data formats (null, strings, booleans) and convert them to valid numbers for comparison.
Any suggestions on how to robustly convert and compare these values as numbers would be greatly appreciated!
n8n:1.100.0