Code:
dataset.sort(function (a, b) {
var nameA = Number(a.field3)||0; //if value is NaN use 0
var nameB = Number(b.field3)||0; //if value is NaN use 0
return (nameA - nameB); //wrong order (nameB - nameA) returns greatest to least
});
Outputs:
[
{
"field1": "val4",
"field2": "val5",
"field4": "2/3/2015"
},
{
"field1": "val6",
"field2": "val7",
"field3": "26.37",
"field4": "4/2/2015"
},
{
"field1": "val1",
"field2": "val2",
"field3": "34.11"
}
]
Field 4:
dataset.sort(function (a, b) {
var nameA = (new Date(a.field4));
if ( isNaN( nameA.getTime() ) ) { //checks if date is invalid
nameA = -10e15;
}
var nameB = (new Date(b.field4));
if ( isNaN( nameB.getTime() ) ) {
nameB = -10e15;
}
return (nameA - nameB);
});
Dataset In:
var dataset = [
{ "field1":"val4", "field2":"val5", "field4":"2/3/2015" },
{ "field1":"val6", "field2":"val7", "field3": "26.37", "field4":"4/2/2015" },
{ "field1":"val1", "field2":"val2", "field3":"34.11" },
{ "field1":"val1", "field2":"val2", "field3":"34.11", "field4":"4/1/2003" }
] ;
Dataset Out:
[
{
"field1": "val1",
"field2": "val2",
"field3": "34.11"
},
{
"field1": "val1",
"field2": "val2",
"field3": "34.11",
"field4": "4/1/2003"
},
{
"field1": "val4",
"field2": "val5",
"field4": "2/3/2015"
},
{
"field1": "val6",
"field2": "val7",
"field3": "26.37",
"field4": "4/2/2015"
}
]