How to Sort an Object Array by Date Property

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.

How to sort array by date In JavaScript?

Parse strings to get Date objects, then sort by compare function.

var a = [
{
"name": "February",
"plantingDate": "2018-02-04T17:00:00.000Z",
},
{
"name": "March",
"plantingDate": "2018-03-04T17:00:00.000Z",
},
{
"name": "January",
"plantingDate": "2018-01-17T17:00:00.000Z",
}
]

a.sort(function(a,b){
return new Date(a.plantingDate) - new Date(b.plantingDate)
})

console.log(a)

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))

Map and sort data by date

let data = [
{
"itemOne":111,
"itemTwo":1,
"itemThree":"2022-02-01T00:00:00.000Z"
},
{
"itemOne":222,
"itemTwo":2,
"itemThree":"2022-01-01T00:00:00.000Z"
},
{
"itemOne":333,
"itemTwo":3,
"itemThree":"2021-12-01T00:00:00.000Z"
},
]
data.sort((a,b)=>{
return new Date(b.itemThree) - new Date(a.itemThree);
})

This sorts your data array according to date.
Hope this is helpful

Javascript sort object array by recent date to oldest date?

You could do something like the following.

const medList = [{
"name": "Insulin",
"data": [{
"dose": 20,
"date": "12/21/2019"
},
{
"dose": 10,
"date": "2/15/2020"
}, {
"dose": 20,
"date": "1/18/2020"
}
]
},
{
"name": "Viagra",
"data": [{
"dose": 20,
"date": "9/9/2019"
},
{
"dose": 10,
"date": "12/15/2020"
}, {
"dose": 20,
"date": "1/22/2020"
}
]
},
]

const sortedViagra = medList[1].data.sort((a, b) => new Date(b.date) - new Date(a.date));

const sortedMeds = medList.map(med => {
return med.data.sort((a, b) => new Date(b.date) - new Date(a.date));
});

console.log('sortedMeds --->', sortedMeds)
console.log('sortedViagra -->', sortedViagra)

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 array of objects by dates and make new arrays which will contain all objects with same date

you can use .reduce(), i leave you this example:

let foo = [
{name: 'first', date: '2020-05-06'},
{name: 'second', date: '2020-04-07'},
{name: 'third', date: '2020-05-06'},
{name: 'fourth', date: '2020-04-07'},
{name: 'fifth', date: '2020-04-09'}
];
let boo = foo.reduce((acc, elem) => {
(acc[elem.date] ??= []).push(elem);
// since OP said they have eslint issues with ??=
// following may be used instead of the above line
// acc[elem.date] = (acc[elem.date] || []).concat([elem])
return acc;
}, {});

console.log('output: ', boo);

How to sort array of objects by date but with most current date first?

function getItemsInAscendingDateOrderAndClosestToNowFirst(arr) {
const time = Date.now();

const [closest, ...rest] = Array
// create a shallow copy in order to
// not mutate the original reference.
.from(arr)
// sort items by date closest to now.
.sort((a, b) => {

const aTime = new Date(a.effectiveDate).getTime();
const bTime = new Date(b.effectiveDate).getTime();

const aDelta = Math.abs(time - aTime);
const bDelta = Math.abs(time - bTime);

return (aDelta - bDelta);
});

return [
closest,
...rest
// sort all other items in ascending date order.
.sort((a, b) =>
new Date(a.effectiveDate).getTime()
- new Date(b.effectiveDate).getTime()
),
];
}

const data = [{
"id": "1",
"effectiveDate": "2023-01-21"
}, {
"id": "2",
"effectiveDate": "2023-02-22"
}, {
"id": "3",
"effectiveDate": "2022-05-04"
}, {
"id": "4",
"effectiveDate": "2022-05-05"
}, {
"id": "5",
"effectiveDate": "2021-01-21"
}, {
"id": "6",
"effectiveDate": "2021-02-22"
}];
const sortedData =
getItemsInAscendingDateOrderAndClosestToNowFirst(data);

console.log({ sortedData });
.as-console-wrapper { min-height: 100%!important; top: 0; }

Sort an array with objects date property

If the date format is always the same, you can just create the string in format YYYYMMDD and then compare -

var data = [{
Title: "Title",
Url: "myUrl",
publishedDate: "19/01/2021"
}, {
Title: "Title 2",
Url: "myUrl",
publishedDate: "17/12/2020"
}, {
Title: "Title 3",
Url: "myUrl",
publishedDate: "11/03/2021"
}, {
Title: "Title 4",
Url: "myUrl",
publishedDate: "11/12/2020"
}]

var sortedData = data.sort(function(a, b) {
a = a.publishedDate.split('/').reverse().join('');
b = b.publishedDate.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
});

console.log(sortedData);

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);


Related Topics



Leave a reply



Submit