使用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 thenameproperties of two objects (aandb) usinglocaleCompare(). This ensures proper sorting for names with special characters and different languages. It returns:- A negative number if
a.namecomes beforeb.name. - A positive number if
a.namecomes afterb.name. - Zero if
a.nameis equal tob.name.
- A negative number if
-
if (nameComparison !== 0): If the names are different, thenameComparisonresult is returned, determining the order. -
return b.age - a.age: If the names are the same, this part compares theageproperties.b.age - a.agesorts 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.
浙公网安备 33010602011771号