I'm not 100% convinced that this is really better than just passing an array to function… but you can wrap the sort in a function and put it on the array prototype. This has the convenience of just being able to call it with dateSort() but lack the flexibility of passing in a callback:
Array.prototype.dateSort = function(desc = true) {
this.sort((a, b) => {
if (!desc) [a, b] = [b,a]
return new Date(b.timestamp) - new Date(a.timestamp);
});
}
// Prevent dateSort from showing up when iterating over object keys:
Object.defineProperty(Array.prototype, 'dateSort',{
enumerable: false
});
let arr = [
{timestamp: '1995-12-17T03:24:00'},
{timestamp: '1995-12-17T01:24:00'},
{timestamp: '1995-12-17T02:24:00'},
{timestamp: '1995-12-17T00:24:00'}
]
arr.dateSort()
console.log(arr)
arr.dateSort(false)
console.log(arr)
for (let i in arr){
// no datesort when enumerating
console.log(i)
}
[...].sort(sortByDate). You should be careful about overwriting existing functions because other libraries or code you use might depend on it.function sortByDate(a, b) { return ... } /* .. */ [...].sort(sortByDate)timestampis oddly specific and it seems unnecessary to pollute the prototype with this. You could create a genericcompareFunction. Even that seems like overhead.[...].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))is readable for he next person reading the code than checking some other file to see what's going on