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.
The code treats values like a.json[fieldName] and b.json[fieldName] as strings, causing incorrect comparisons (e.g., '99' > '998' is true).
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 99 is correctly identified as less than 998.
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!
Are you sure a.json[fieldName] and b.json[fieldName] are actually referencing the values you think they are? Are your objects structured like this?
a
{
"json": {
"interact_info.liked_count": 99
}
}
b
{
"json": {
"interact_info.liked_count": 998
}
}
You may be expecting the fieldName to support dot notation for nested objects, but I don’t think it will. This code might help you see what’s happening.
Comparing the objects with weird attribute names works.
Comparing the nested objects (what you might expect the dot-notation fieldName is referencing) does not.
let firstObjectWithWeirdAttributeName =
{
"json": {
"interact_info.liked_count": 99
}
}
let secondObjectWithWeirdAttributeName =
{
"json": {
"interact_info.liked_count": 998
}
}
let firstNestedObject =
{
"json": {
"interact_info": {
"liked_count": 99
}
}
}
let secondNestedObject =
{
"json": {
"interact_info": {
"liked_count": 998
}
}
}
let fieldName = 'interact_info.liked_count';
function javaLikeSortCompareFunction(a, b) {
if (a.json[fieldName] < b.json[fieldName]) {
return -1;
}
if (a.json[fieldName] > b.json[fieldName]) {
return 1;
}
return 0;
}
let results = {
"json": {
"resultValueDotInAttributeName":
javaLikeSortCompareFunction(firstObjectWithWeirdAttributeName,
secondObjectWithWeirdAttributeName),
"resultValueNestedObjects":
javaLikeSortCompareFunction(firstNestedObject,
secondNestedObject)
}
};
return [firstObjectWithWeirdAttributeName,
secondObjectWithWeirdAttributeName,
firstNestedObject,
secondNestedObject,
results];