Sort array of objects with date field by date
You don't really need lodash. You can use JavaScript's Array.prototype.sort
method.
You'll need to create Date
objects from your date strings before you can compare them.
var myArray = [{ name: "Joe Blow", date: "Mon Oct 31 2016 00:00:00 GMT-0700 (PDT)"}, { name: "Sam Snead", date: "Sun Oct 30 2016 00:00:00 GMT-0700 (PDT)"}, { name: "John Smith", date: "Sat Oct 29 2016 00:00:00 GMT-0700 (PDT)"}];
myArray.sort(function compare(a, b) { var dateA = new Date(a.date); var dateB = new Date(b.date); return dateA - dateB;});
console.log(myArray);
How to sort an object array by date property?
Simplest Answer
array.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
More Generic Answer
array.sort(function(o1,o2){
if (sort_o1_before_o2) return -1;
else if(sort_o1_after_o2) return 1;
else return 0;
});
Or more tersely:
array.sort(function(o1,o2){
return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;
});
Generic, Powerful Answer
Define a custom non-enumerable sortBy
function using a Schwartzian transform on all arrays :
(function(){
if (typeof Object.defineProperty === 'function'){
try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
}
if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;
function sb(f){
for (var i=this.length;i;){
var o = this[--i];
this[i] = [].concat(f.call(o,o,i),o);
}
this.sort(function(a,b){
for (var i=0,len=a.length;i<len;++i){
if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
}
return 0;
});
for (var i=this.length;i;){
this[--i]=this[i][this[i].length-1];
}
return this;
}
})();
Use it like so:
array.sortBy(function(o){ return o.date });
If your date is not directly comparable, make a comparable date out of it, e.g.
array.sortBy(function(o){ return new Date( o.date ) });
You can also use this to sort by multiple criteria if you return an array of values:
// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };
See http://phrogz.net/JS/Array.prototype.sortBy.js for more details.
Sort an array with different objects by date in JS?
You can make use of Array.prototype.sort()
:
const array = [{
type: 'type1',
created_at: '2021-07-31'
}, {
type: 'type2',
order_date: '2021-07-13'
}, {
type: 'type2',
order_date: '2021-07-07'
}, {
type: 'type1',
created_at: '2021-08-05'
}, {
type: 'type3',
updated_at: '2021-09-05'
}];
const res = array.sort(function(a, b) {
return new Date(b.created_at ?? b.order_date ?? b.updated_at) - new Date(a.created_at ?? a.order_date ?? a.updated_at);
})
console.log(res);
Angular 6 Sort Array of object by Date
in addition to cryptic's answer, you will likely want to wrap the sorted values in an accessor for including in the template, adding a getter in your typescript class:
public get sortedArray(): YourItemType[] {
return this.myArr.sort(...);
}
and in the template:
<app-item *ngFor="let item of sortedArray"></app-item>
alternately, you can sort the array as you get it into your component class and store the sorted version there, however the accessor pattern can be quite useful for dynamic sorting.
Sort array of objects by date field
usort($array, function($a, $b) {
return strtotime($a['date']) - strtotime($b['date']);
});
Or if you don't have PHP 5.3:
function cb($a, $b) {
return strtotime($a['date']) - strtotime($b['date']);
}
usort($array, 'cb');
How to sort an array of objects by date?
As has been pointed out in the comments, the definition of recent isn't correct javascript.
But assuming the dates are strings:
var recent = [
{id: 123,age :12,start: "10/17/13 13:07"},
{id: 13,age :62,start: "07/30/13 16:30"}
];
then sort like this:
recent.sort(function(a,b) {
return new Date(a.start).getTime() - new Date(b.start).getTime()
});
More details on sort function from W3Schools
How to sort an array of objects by 'moment' date values?
Use Moment's diff
array.sort((a, b) => moment(a.date, 'DD-MM-YYYY').diff(moment(b.date, 'DD-MM-YYYY')))
Sort array of objects by closest date
What you need to do is work out how far each date is away from today and use this to sort the items, there may be a more elegant way, but this (I think) works. Basically use abs()
to ensure all differences are +ve and take each date away from today...
usort($arr, function($a, $b) {
return (abs(strtotime('today') - strtotime($a->date))
- (abs(strtotime('today') - strtotime($b->date))));
});
JQuery Sorting array of object using date
If lastModifiedDate
is numberic value of timestamp then why need to compare date object of those timestamps you can compare those numbers only for efficient execution of sort as below.
completeData.sort(function(a, b){
return a.lastModifiedDate - b.lastModifiedDate;
});
When you need to display date formate you can use Date object for presentation purpose.
Sort array of objects using multiple date properties
By looking at the js sort
documentation you'll see that sort is taking a function as parameter which :
- Return a positive integer if the first object is bigger than the second one
- Return 0 if the two objects are the same
- Return a negative integer if the first object is smaller than the second one.
Knowing that, let's build the function together :
First, we'd like to get the highest date for on object.
For that, i would recommend using Math.max which takes an array and returns the biggest parameters.
Here it works because js understand date as integers.
function highestDate(obj){
return Math.max(obj.timestamp1,obj.timestamp2,obj.timestamp3)
}
Now let's build the sort function.
function compare(a,b){
return highestDate(b) - highestDate(a)
}
here is a snipper for testing :
function highestDate(obj){
return Math.max(obj.timestamp1,obj.timestamp2,obj.timestamp3)
}
function compare(a,b){
return highestDate(b) - highestDate(a)
}
let obj1={
id:1,
timestamp1 : new Date(2001,1,1),
timestamp2 : new Date(2002,1,1),
timestamp3 : new Date(2003,1,1) //third highest date
}
let obj2={
id:2,
timestamp1 : new Date(1997,1,1),
timestamp2 : new Date(2004,1,1),//second highest date
timestamp3 : new Date(2003,1,1)
}
let obj3={
id:3,
timestamp1 : new Date(1991,1,1),
timestamp2 : new Date(2001,1,1),
timestamp3 : new Date(2005,1,1) //highest date
}
let arr = [obj1,obj2,obj3]
console.log(arr.sort(compare))
Related Topics
Allow Users to Download Files Outside Webroot
How to Find First Day of the Next Month and Remaining Days Till This Date with PHP
Utf-8 in PHP Regular Expressions
Why Is the PHP String Concatenation Operator a Dot (.)
Large Hex Values with PHP Hexdec
How to Redefine a Type Hint to a Descendant Class When Extending an Abstract Class
Installing Imagemagick Extension with PHP/Windows
Array Combine Three or More Arrays with PHP
How to Find Error Log Files for PHP
How to Convert Multiple <Br/> Tag to a Single <Br/> Tag in PHP
How to Display PHP Errors in Code Output
Verify Password Hash in Nodejs Which Was Generated in PHP
Subtracting a Certain Number of Hours, Days, Months or Years from Date