【问题标题】:how to sort an array of objects based on property value [duplicate]如何根据属性值对对象数组进行排序[重复]
【发布时间】:2021-07-14 23:30:24
【问题描述】:

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

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]

【问题讨论】:

标签: javascript arrays class sorting


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    只需使用您知道的排序算法,但现在比较对象的键值: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();
              } 
        } 
    } 
    

    【讨论】:

    • 嗨,感谢您的回答,我只需要澄清一两件事,对不起,我在这方面有点初学者。我了解您用来遍历数组中每个值的前两个 for 循环。我不太明白的是if语句。为什么它说'carsArray[j + 1].weight,+ 1有什么用?我也可以假设 swapTheObjects();将是我必须自己编写的方法吗?
    • 它将j-th 元素与右边的元素(j + 1-th)进行比较,如果j-th 元素的值大于j + 1- th - 你只需要将j-th 元素放在j + 1-th 的位置上,将j + 1-th 放在j-th 的位置上。为了更好地理解,请观看 YouTube 上有关冒泡排序的视频,因为我无法解释得这么清楚。
    猜你喜欢
    • 2017-07-18
    • 2017-04-06
    • 2018-11-14
    • 2020-09-22
    • 2012-10-22
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多