I know similar question is asked before and I referred to this one here: sort json object in javascript but I still cannot find answer to my question. So here I go. I have an JSON object structure as below:
[
{
"toothNumber": "01",
"name": "John"
},
{
"toothNumber": "18",
"name": "John"
},
{
"toothNumber": "19",
"name": "John"
},
{
"toothNumber": "17",
"name": "John"
},
{
"toothNumber": "01,32",
"name": "John"
},
{
"toothNumber": "25,32",
"name": "John"
},
{
"toothNumber": "",
"name": "John"
},
{
"toothNumber": "15",
"name": "John"
}
]
When I use the below code to sort, I do not get expected results:
json.sort(function(a, b){
return a.toothNumber - b.toothNumber;
});
Below, is the actual result which is not the one I expected. Any help will be appreciated.
Actual Result:
[
{
"toothNumber": "",
"name": "John"
},
{
"toothNumber": "01",
"name": "John"
},
{
"toothNumber": "15",
"name": "John"
},
{
"toothNumber": "17",
"name": "John"
},
{
"toothNumber": "18",
"name": "John"
},
{
"toothNumber": "19",
"name": "John"
},
{
"toothNumber": "01,32",
"name": "John"
},
{
"toothNumber": "25,32",
"name": "John"
}
]
Expected Result:
[
{
"toothNumber": "",
"name": "John"
},
{
"toothNumber": "01",
"name": "John"
},
{
"toothNumber": "01,32",
"name": "John"
},
{
"toothNumber": "15",
"name": "John"
},
{
"toothNumber": "17",
"name": "John"
},
{
"toothNumber": "18",
"name": "John"
},
{
"toothNumber": "19",
"name": "John"
},
{
"toothNumber": "25,32",
"name": "John"
}
]
CodePudding user response:
Sort with string, instead of number comparison.
const json = [ { "toothNumber": "01", "name": "John" }, { "toothNumber": "18", "name": "John" }, { "toothNumber": "19", "name": "John" }, { "toothNumber": "17", "name": "John" }, { "toothNumber": "01,32", "name": "John" }, { "toothNumber": "25,32", "name": "John" }, { "toothNumber": "", "name": "John" }, { "toothNumber": "15", "name": "John" }];
json.sort(function(a, b){
return a.toothNumber > b.toothNumber ? 1 : (a.toothNumber === b.toothNumber ? 0 : -1 );
});
console.log(json);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You could just do this
const json = [ { "toothNumber": "01", "name": "John" }, { "toothNumber": "18", "name": "John" }, { "toothNumber": "19", "name": "John" }, { "toothNumber": "17", "name": "John" }, { "toothNumber": "01,32", "name": "John" }, { "toothNumber": "25,32", "name": "John" }, { "toothNumber": "", "name": "John" }, { "toothNumber": "15", "name": "John" }];
json.sort(function(a, b) {
return a.toothNumber.split(",")[0] - b.toothNumber.split(",")[0];
});
console.log(json)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>