How to sort an array of objects by multiple fields?
You could use a chained sorting approach by taking the delta of values until it reaches a value not equal to zero.
var data = [{ h_id: "3", city: "Dallas", state: "TX", zip: "75201", price: "162500" }, { h_id: "4", city: "Bevery Hills", state: "CA", zip: "90210", price: "319250" }, { h_id: "6", city: "Dallas", state: "TX", zip: "75000", price: "556699" }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500" }];
data.sort(function (a, b) {
return a.city.localeCompare(b.city) || b.price - a.price;
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sort array of objects by multiple properties of string type
The test should be (assuming your date format is dd/mm/yyyy
)
if (a.name > b.name) return 1;
if (a.name < b.name) return -1;
let [a_dd, a_mm, a_yy] = a.joindate.split("/");
let [b_dd, b_mm, b_yy] = b.joindate.split("/");
if (a_yy !== b_yy) return a_yy - b_yy;
if (a_mm !== b_mm) return a_mm - b_mm;
if (a_dd !== b_dd) return a_dd - b_dd;
return 0;
Sort array of objects by multiple fields using javascript sort()
You can sort multiple fields by ||
const data = [
{ num: 0.28, status: true },
{ num: 0.21, status: false },
{ num: 0.2, status: true },
{ num: 0.19, status: false },
{ num: 0.24, status: true },
{ num: 0.23, status: false },
{ num: 0.29, status: false },
{ num: 0.25, status: true },
];
const result = data.sort((a, b) => b.status - a.status || a.num - b.num)
console.log(result)
Sort an array of objects by multiple fields
You may use this multi sort function from https://stackoverflow.com/a/22672370/3807365 - basically you just tell it which fields to sort by and you shall get a sorting method to pass to your Array.sort.
let objs = [{
name: 'Mark',
age: 31,
id: 3,
},
{
name: 'Anne',
age: 20,
id: 2,
},
{
name: 'James',
age: 40,
id: 4,
},
{
name: 'Jerry',
age: 30,
id: 1,
},
{
name: 'Lucy',
age: 30,
id: 5,
},
{
name: 'Mark',
age: 30,
id: 6,
},
]
function getSortMethod() {
var _args = Array.prototype.slice.call(arguments);
return function(a, b) {
for (var x in _args) {
var ax = a[_args[x].substring(1)];
var bx = b[_args[x].substring(1)];
var cx;
ax = typeof ax == "string" ? ax.toLowerCase() : ax / 1;
bx = typeof bx == "string" ? bx.toLowerCase() : bx / 1;
if (_args[x].substring(0, 1) == "-") {
cx = ax;
ax = bx;
bx = cx;
}
if (ax != bx) {
return ax < bx ? -1 : 1;
}
}
}
}
objs.sort(getSortMethod('+name', '+age'));
console.log(objs)
.as-console-wrapper {
max-height: 100% !important;
}
Javascript: How to sort array of objects by multiple fields?
I'd start off with a function which sorts 2 objects by a field and descending bool
const sortBy = (a,b,field,desc) => {
if(a[field]<b[field]) return desc ? 1 : -1
else if(a[field]>b[field]) return desc ? -1 : 1
else return 0;
};
You can then use this in a loop over your sortFields
(and descending
) arrays:
const arrayToSort = [
{
Country: "Cyprus",
Date: new Date(2001, 0, 1),
CreateBy: "William",
},
{
Country: "Belarus",
Date: new Date(1999, 0, 1),
CreateBy: "Yuliana",
},
{
Country: "Denmark",
Date: new Date(2019, 0, 1),
CreateBy: "Ava",
},
{
Country: "Albania",
Date: new Date(2000, 0, 1),
CreateBy: "Zachary",
}
];
const sortFields = ["Country", "CreateBy", "Date"];
const descending = [true, false, true];
const sortBy = (a,b,field,desc) => {
if(a[field]<b[field]) return desc ? 1 : -1
else if(a[field]>b[field]) return desc ? -1 : 1
else return 0;
};
const result = arrayToSort.sort( (a,b) => {
for(var i=0;i<sortFields.length;i++){
var res = sortBy(a,b, sortFields[i], descending[i]);
if(res != 0) return res;
}
return 0;
})
console.log(result);
How to sort an array of objects by multiple date fields?
You need to sort based on
- whether
date1
exists - then based on
date1
value - then based on
date2
value
Since the dates are in ISO format, you can do string comparison to sort
const input=[{id:"1",date1:"2022-03-21T18:59:36.641Z",date2:"2022-03-17T18:59:36.641Z",},{id:"2",date1:"2022-03-20T18:59:36.641Z",date2:"2022-03-17T18:59:36.641Z",},{id:"3",date2:"2022-03-17T18:59:36.641Z",},{id:"4",date2:"2022-03-15T18:59:36.641Z",}];
input.sort((a,b) =>
( ('date1' in b) - ('date1' in a) )
|| (a.date1 ?? '').localeCompare(b.date1 ?? '')
|| a.date2.localeCompare(b.date2)
)
console.log(input)
Sorting of an array of objects by multiple fields in JavaScript varies based on object position in the input Array
You could take a simplified approach and chain all sorting crieria by taking the delta or use a string comparison.
const
getISO = (date, time) => `${date.slice(3, 5)}-${date.slice(0, 2)}-${date.slice(6, 10)}T${time}`;
data = [{ name: "Pass9884881", fld1d: 10, fld2d: 25, fld4d: 383, fld3d: 626490, fld5a: 0, date: "09/27/2021", time: "18:23:31" }, { name: "Driver1", fld1d: "10", fld2d: 25, fld4d: 356, fld3d: 559650, fld5a: 0, date: "10/18/2021", time: "14:48:17" }, { name: "Driver321", fld1d: 10, fld2d: 22, fld4d: 346, fld3d: 554400, fld5a: 1, date: "08/08/2021", time: "22:35:03" }, { name: "Driverxyz", fld1d: 9, fld2d: 25, fld4d: 350, fld3d: 497190, fld5a: 0, date: "07/26/2021", time: "14:23:33" }, { name: "Pass1974761", fld1d: "9", fld2d: 25, fld4d: 316, fld3d: 477290, fld5a: 0, date: "10/11/2021", time: "19:20:33" }, { name: "Pass7374147", fld1d: "9", fld2d: 23, fld4d: 279, fld3d: 376750, fld5a: 0, date: "10/10/2021", time: "20:13:15" }, { name: "Driver0", fld1d: 8, fld2d: 25, fld4d: 286, fld3d: 435940, fld5a: 0, date: "07/26/2021", time: "12:31:42" }, { name: "Pass1536735", fld1d: "8", fld2d: 25, fld4d: 236, fld3d: 329880, fld5a: 0, date: "10/09/2021", time: "17:19:14" }, { name: "#xxxxyyyy", fld1d: "10", fld2d: 25, fld4d: 329, fld3d: 500440, fld5a: 0, date: "11/04/2021", time: "00:04:17" }, { name: "Pass7668209", fld1d: "8", fld2d: 24, fld4d: 203, fld3d: 267150, fld5a: 0, date: "10/09/2021", time: "00:22:18" }],
data.sort((a, b) =>
b.fld1d - a.fld1d ||
b.fld2d - a.fld2d ||
b.fld3d - a.fld3d ||
b.fld4d - a.fld4d ||
a.fld5a - b.fld5a ||
getISO(a.date, a.time).localeCompare(getISO(b.date, b.time))
);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related Topics
Firebase Query If Child of Child Contains a Value
$(Document).Ready Equivalent Without Jquery
Weird Behavior With Objects & Console.Log
Detecting an Undefined Object Property
How to Update Nested State Properties in React
How to Access React Instance (This) Inside Event Handler
Is There a "Null Coalescing" Operator in JavaScript
Explanation of 'Let' and Block Scoping With For Loops
How to Access Post Form Fields in Express
"Cross Origin Requests Are Only Supported For Http." Error When Loading a Local File
How to Add a Delay in a JavaScript Loop
When Is .Then(Success, Fail) Considered an Antipattern For Promises
What Does the Exclamation Mark Do Before the Function
Window.Onload VS Document.Onload
Facebook Js Sdk'S Fb.API('/Me') Method Doesn't Return the Fields I Expect in Graph API V2.4+