Sort array of objects by single key with date value
You can use Array.sort
.
Here's an example:
var arr = [{
"updated_at": "2012-01-01T06:25:24Z",
"foo": "bar"
},
{
"updated_at": "2012-01-09T11:25:13Z",
"foo": "bar"
},
{
"updated_at": "2012-01-05T04:13:24Z",
"foo": "bar"
}
]
arr.sort(function(a, b) {
var keyA = new Date(a.updated_at),
keyB = new Date(b.updated_at);
// Compare the 2 dates
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});
console.log(arr);
Sorting arrays numerically by object property value
Use Array.prototype.sort(), eg
myArray.sort((a, b) => a.distance - b.distance)
The sort()
method accepts a comparator function. This function accepts two arguments (both presumably of the same type) and it's job is to determine which of the two comes first.
It does this by returning an integer
- Negative (less-than zero): The first argument comes first
- Positive (greater-than zero): The second argument comes first
- Zero: The arguments are considered equal for sorting
When you're dealing with numeric values, the simplest solution is to subtract the second value from the first which will produce an ascending order result.
Sort array of objects by string property value
It's easy enough to write your own comparison function:
function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}
objs.sort( compare );
Or inline (c/o Marco Demaio):
objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))
Or simplified for numeric (c/o Andre Figueiredo):
objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort
How to sort array of object based on key that is date using javascript?
You need to use Array.sort()
to sorting array. So use it and in function get key of object (date) using Object.keys()
and convert it to date object and then compare it.
var res = arr.sort((a,b) => new Date(Object.keys(a)[0]) - new Date(Object.keys(b)[0]));
var arr = [ {'12-11-2018': 'NA' }, { '12-05-2018': 'NA' }, { '12-09-2018': 'pass' }, { '12-07-2018': 'pass' }, { '12-10-2018': 'pass' }, { '12-08-2018': 'pass' }, { '12-06-2018': 'pass' } ];var res = arr.sort((a,b) => new Date(Object.keys(a)[0]) - new Date(Object.keys(b)[0]));console.log(res);
Sorting an array of objects by property values
Sort homes by price in ascending order:
homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});
Or after ES6 version:
homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
Some documentation can be found here.
For descending order, you may use
homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));
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);
Sort array of object by key in date string format
Your code is almost fine actually, the only missing piece is Object.fromEntries
:
sorted = (obj).map(val =>
Object.fromEntries(
Object.entries(val).sort((a, b) => {
const aa = a[0].split('/').reverse();
const bb = b[0].split('/').reverse();
return (aa > bb) - (aa < bb);
})))
Sort an array of object with key in JavaScript
Just this will work.
myArray.sort((a,b) => Object.entries(a)[0] < Object.entries(b)[0] ? -1 : 1);
Running example below:
const myArray = [
{ '2022-03-31': '32.2' },
{ '2022-04-01': '32.23' },
{ '2022-04-02': '32.9' },
{ '2022-03-30': '32.253' },
{ '2022-04-03': '32.253' },
{ '2022-03-18': '32.253' },
{ '2021-06-31': '32.37' }
];
myArray.sort((a,b) => Object.entries(a)[0] < Object.entries(b)[0] ? -1 : 1);
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.
Sorting array of objects according to the date
You might be encountering an issue with new Date(...)
not handling strings of this format since it's not a standard format. new Date("02-04-2020")
interprets it as February 4, 2020, and new Date("16-04-2020")
produces an error. It's seeming to use American date formats here, where we backwardsly use month before day.
If your dates were in the format yyyy-mm-dd
, then new Date(...)
would work properly, so if you're able to change that, that'll be the smoothest route. If you cannot change the format, you'll want to consider changing the sorting thusly:
const sorted_array = data
.map(addSortableColumn)
.sort(bySortColumn)
.map(removeSortableColumn);
function addSortableColumn(item) {
const [day, month, year] = item.date.split('-');
return { ...item, _sortBy: year + month + day };
}
function bySortColumn(a, b) {
return a._sortBy.localeCompare(b._sortBy);
}
function removeSortableColumn(item) {
const { _sortBy, ...otherProps } = item;
return otherProps;
}
(if you don't care about removing the sort column, you can skip that last step)
Update
If you need to preserve object prototypes, it was correctly pointed out that spread syntax destroys this. Another approach that I actually like even better is to store the sort columns in a separate map. The reason why it's even being stored is to avoid the sort keys needing to be computed multiple times.
const sortKeys = new Map();
const sorted_array = data.slice().sort(byDDMMYYYY);
function byDDMMYYYY(a, b) {
return getSortKey(a).localeCompare(getSortKey(b));
}
function getSortKey(item) {
let key = sortKeys.get(item);
if (!key) {
const [day, month, year] = item.date.split('-');
key = year + month + day;
sortKeys.set(item, key);
}
return key;
}
Related Topics
How to Synchronize a Sequence of Promises
Getting Around X-Frame-Options Deny in a Chrome Extension
JavaScript Setinterval and 'This' Solution
Promise.All Consumes All My Ram
How to Pass Data from a Page to Another Page Using React Router
How to Set the Value Property in Angularjs' Ng-Options
How to Check a Radio Button with Jquery
How to Get Element by Xpath Using JavaScript in Selenium Webdriver
Jquery - Setting the Selected Value of a Select Control via Its Text Description
Concrete JavaScript Regular Expression for Accented Characters (Diacritics)
How to Get the Non-Enumerable Inherited Property Names of an Object
Using Jquery's Ajax Method to Retrieve Images as a Blob
JavaScript Document.Getelementsbyclassname Compatibility with Ie
JavaScript Filter Array of Objects
Display Posts in Descending Posted Order
Why and When Do We Need to Bind Functions and Eventhandlers in React
Is the Underscore Prefix for Property and Method Names Merely a Convention