I have for example this dataset:
const order = [
{ key: "job", direction: "ascending" },
{ key: "age", direction: "descending" },
];
const records = [
{ name: "christian", age: 40, job: "developer" },
{ name: "andrew", age: 48, job: "developer" },
{ name: "elisabeth", age: 31, job: "floor manager" },
{ name: "oscar", age: 61, job: "floor manager" },
{ name: "gisela", age: 51, job: "area manager" },
{ name: "buffy", age: 27, job: "trainee" },
{ name: "carl", age: 23, job: "trainee" },
];
I need to sort the records array according to the criteria from order array.
I ended up with this solution:
const sorted = records.sort(
(recordA, recordB) =>
recordA.job.localeCompare(recordB.job) || recordA.age - recordB.age
);
But I cant understand how can I use the order array instead of hardcoded the job and age properties. The order array can have many properties.
orderarray also contained an entry that tells you if the property is to be sorted numerically or lexicographically, at least if you want to keep usinglocalCompareand-. Alternatively, everything can be generalized with(a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0).