Sorting Data That Has Blanks Or Gaps
I have data like this: var dataset = [ { 'field1':'val1', 'field2':'val2', 'field3':'34.11' }, { 'field1':'val4', 'field2':'val5', 'field4':'2/3/2015' }, { 'field1':'val6',
Solution 1:
Code:
dataset.sort(function (a, b) {
var nameA = Number(a.field3)||0; //if value is NaN use 0var nameB = Number(b.field3)||0; //if value is NaN use 0return (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 = (newDate(a.field4));
if ( isNaN( nameA.getTime() ) ) { //checks if date is invalid
nameA = -10e15;
}
var nameB = (newDate(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"}]
Solution 2:
Here is a general sorting function.
If you have a missing field - this field gets first. Otherwise - the order will be based on the localeCompare
of the values of the same fields.
var dataset = [
{ "field1":"val1", "field2":"val2", "field3":"34.11" },
{ "field1":"val4", "field2":"val5", "field4":"2/3/2015" },
{ "field1":"val6", "field2":"val7", "field3": "26.37", "field4":"4/2/2015" }
] ;
dataset.sort(function (a, b) {
aFields = Object.keys(a).sort()
bFields = Object.keys(b).sort()
i = 0;
if (aFields[i] == bFields[i]) {
if (a[aFields[i]].localeCompare(b[bFields[i]]) == 0) {
i++;
} else {
return a[aFields[i]].localeCompare(b[bFields[i]]);
}
} else {
return bFields[i].localeCompare(aFields[i]);
}
});
console.log(dataset)
Post a Comment for "Sorting Data That Has Blanks Or Gaps"