如何根据属性值对对象数组进行排序

时间:2021-04-20 18:35:47

标签: javascript arrays class sorting

关于下面的代码块,我有一个类用于创建多个对象,每个对象都包含有关特定汽车的一些基本信息。我最后创建了这些对象的数组。我如何根据一个值(比如它们的重量)按从最小到最重的升序来整理这个对象数组。

class raceCar {
    constructor(name, weight, lenght, width, height, horsePower, torque, colour){
        this._name = name;
        this._weight = weight;
        this._lenght = lenght;
        this._width = width;
        this._height = height;
        this._horsePower = horsePower;
        this._torque = torque;
        this._colour = colour;
    }

        get name(){
            return this._name;
        }

        get weight(){
            return this._weight;
        }

        get lenght(){
            return this._lenght;
        }

        get width(){
            return this._width;
        }

        get height(){
            return this._height;
        }

        get horsePower(){
            return this._horsePower;
        }

        get torque(){
            return this._torque
        }

        get colour(){
            return this._colour
        }

} 

const a45s = new raceCar ('a45s', 1550, 4445, 1850, 1412, 421, 500, 'black');
const m135i = new raceCar ('m135i', 1525, 4319, 1799, 1434, 306, 450, 'blue')
const golfR = new raceCar ('golfR', 1408, 4263, 1799, 1465, 310, 380, 'green')
const m240i = new raceCar ('240i', 1475, 4454, 1774, 1408, 340, 500, 'blue')
const cupra = new raceCar ('cupra', 1490, 4398, 1799, 1442, 300, 400, 'white')

var carArray = [a45s, m135i, golfR, m240i, cupra]

2 个答案:

答案 0 :(得分:0)

只需调用 Array sort() 方法。像这样:

carArray = carArray.sort((carA,carB) => carB.weight - carA.weight); // ascending order
carArray = carArray.sort((carA,carB) => carA.weight - carB.weight); // descending order

答案 1 :(得分:0)

只需使用您知道的排序算法,但现在比较对象的键值:carsArray[i].weight。 冒泡排序的例子如下:

for(let i = 0; i < carsArray.length; i++){
    for(let j = 0; j < carsArray.length - 1; j++){
          if(carsArray[j].weight < carsArray[j + 1].weight){
              swapTheObjects();
          } 
    } 
}