I am writing my dates of birth in the following manner:
I wanted to sort it using
A working version with optional time values.
var obj = [{
"id": 1,
"dateOfBirth": "1.7.1990"
},
{
"id": 4,
"dateOfBirth": "4.02.1976 14:37"
}, {
"id": 2,
"dateOfBirth": "28.10.1950 2:15"
}
];
console.log(
obj.sort(function(a, b) {
return parseDate(a.dateOfBirth) -
parseDate(b.dateOfBirth);
})
);
function parseDate(str) {
var tokens = str.split(/\D/);
while (tokens.length < 5)
tokens.push(0);
return new Date(tokens[2], tokens[1]-1, tokens[0], tokens[3]||0, tokens[4]||0);
}
Since you just have the year/month/day, it's pretty trivial to split up the dateOfBirth string, convert to a single number, and sort by that number, without any need to mess with Dates:
var obj = [{
"id": 1,
"dateOfBirth": "1.7.1990"
}, {
id: 2,
dateOfBirth: "28.10.1950"
}, {
"id": 4,
"dateOfBirth": "4.02.1976"
}];
function valueFromDOBString(str) {
const values = str.split('.').map(Number);
return values[0] + values[1] * 100 + values[2] * 10000;
}
const sortedObj = obj.sort((a, b) => {
return valueFromDOBString(b.dateOfBirth) - valueFromDOBString(a.dateOfBirth);
});
console.log(sortedObj);