谁能帮我把下面的数组按升序/降序排序?数组将根据每个分组(使用brand分组)中的最高数字进行排序。每组中的数字也要排序:
original_array = [
{ brand: "Ford", number: "1", },
{ brand: "BMW", number: "1", },
{ brand: "BMW", number: "5", },
{ brand: "BMW", number: "20",},
{ brand: "Toyota", number: "10",}
];
desc_order = [
{ brand: "BMW", number: "20",},
{ brand: "BMW", number: "5", },
{ brand: "BMW", number: "1", },
{ brand: "Toyota", number: "10",},
{ brand: "Ford", number: "1", }
];
asc_order = [
{ brand: "Ford", number: "1", },
{ brand: "Toyota", number: "10",},
{ brand: "BMW", number: "1", },
{ brand: "BMW", number: "5", },
{ brand: "BMW", number: "20",}
];
由于输出中的品牌顺序取决于其组中的最大值,因此我建议首先创建一个列出每个品牌的最大数量的对象。
然后使用它来排序,使用以下排序顺序:
- 首先按品牌的最大值
- 当该值相等时,按品牌名称(因为几个品牌可能有相同的最大数量)
- 当该值相等时,通过数字本身
实现:
const array = [ { brand: "Ford", number: "1", }, { brand: "BMW", number: "1", }, { brand: "BMW", number: "5", }, { brand: "BMW", number: "20", }, { brand: "Toyota", number: "10", } ];
// First collect the maximum values per brand as an aggregate:
const aggr = {};
for (let {brand, number} of array) {
aggr[brand] = Math.max(number, aggr[brand] ?? number);
}
// Ascending
array.sort((a, b) => aggr[a.brand] - aggr[b.brand]
|| a.brand.localeCompare(b.brand)
|| a.number - b.number);
console.log(array);
// Descending
array.sort((a, b) => aggr[b.brand] - aggr[a.brand]
|| b.brand.localeCompare(a.brand)
|| b.number - a.number);
console.log(array);