使用js写个方法,把下列数组对象按多字段排序,name升序,age降序
function sortByMultipleFields(arr) {
return arr.sort((a, b) => {
// First sort by name in ascending order
const nameComparison = a.name.localeCompare(b.name);
if (nameComparison !== 0) {
return nameComparison;
}
// If names are equal, sort by age in descending order
return b.age - a.age;
});
}
// Example usage:
const data = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 30 },
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 35 }
];
const sortedData = sortByMultipleFields(data);
console.log(sortedData);
/* Expected output:
[
{ name: 'Alice', age: 30 },
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 35 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 30 }
]
*/
Explanation:
-
sortByMultipleFields(arr)
function: This function takes the array of objects as input. -
arr.sort((a, b) => ...)
: Thesort()
method is used to sort the array in place. It takes a comparison function as an argument. -
a.name.localeCompare(b.name)
: This compares thename
properties of two objects (a
andb
) usinglocaleCompare()
. This ensures proper sorting for names with special characters and different languages. It returns:- A negative number if
a.name
comes beforeb.name
. - A positive number if
a.name
comes afterb.name
. - Zero if
a.name
is equal tob.name
.
- A negative number if
-
if (nameComparison !== 0)
: If the names are different, thenameComparison
result is returned, determining the order. -
return b.age - a.age
: If the names are the same, this part compares theage
properties.b.age - a.age
sorts in descending order (larger ages first). If you wanted ascending order for age, you would usea.age - b.age
.
Key improvements over simpler solutions:
localeCompare()
: Handles string comparisons correctly for different languages and special characters, unlike a simple<
or>
comparison.- Clear and concise: The code is easy to understand and maintain.
- Efficient for smaller arrays: The built-in
sort()
is generally efficient enough for most common use cases. For extremely large datasets, you might consider more optimized sorting algorithms.
This improved version addresses potential issues with string comparisons and provides a more robust and reliable way to sort by multiple fields. It also explains the logic clearly, making it easier to adapt for other sorting criteria.