A list of fields that specify the object comparison. This can be a direct field name or an object specifier for advanced configuration. Multiple field names or objects are also supported, in which case the new comparator will create a lexicographic order based on these fields.
A field name is considered to be a string for member attributes, or a number to indicate a particular index of an array within the array to be sorted.
The default comparison function compares fields using the builtin <
and >
operators, but a custom
compare function can be specified when using the object notation.
The order returned by the comparator is ascending by default.
the new comparator function.
const data = [
{ name: "B", age: 21 },
{ name: "A", age: 21 },
{ name: "C", age: 20 }
];
// Orders by age, or if ages are equal, by name.
data.sort(compareFields("age", "name"));
const data = [
{ name: "B", age: 21 },
{ name: "A", age: 21 },
{ name: "C", age: 20 }
];
data.sort(compareFields({ field: "age", reverse: true }, "name"));
const data = [
[1, 2],
[1, 3],
[2, 3],
];
// Orders by array item at index 1, or by index 0 if the other values are equal.
data.sort(compareFields(1, 0));
Creates a new comparator function that compares the fields of its input arguments using the given specification. The function can then be used, for example, in calls to Array.sort().