使用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:

  1. sortByMultipleFields(arr) function: This function takes the array of objects as input.

  2. arr.sort((a, b) => ...): The sort() method is used to sort the array in place. It takes a comparison function as an argument.

  3. a.name.localeCompare(b.name): This compares the name properties of two objects (a and b) using localeCompare(). This ensures proper sorting for names with special characters and different languages. It returns:

    • A negative number if a.name comes before b.name.
    • A positive number if a.name comes after b.name.
    • Zero if a.name is equal to b.name.
  4. if (nameComparison !== 0): If the names are different, the nameComparison result is returned, determining the order.

  5. return b.age - a.age: If the names are the same, this part compares the age properties. b.age - a.age sorts in descending order (larger ages first). If you wanted ascending order for age, you would use a.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.

posted @ 2024-12-12 09:32  王铁柱6  阅读(6)  评论(0编辑  收藏  举报