简体   繁体   中英

How to reorder objects in an array in typescript?

I am having an array of objects. The objects within the array represent car model and the price. I would like to reorder the objects within the array, so that the list should follow models SEDAN, followed by CITROEN, then SUZUKI, followed by MERCEDES.

The following is my code.

     enum Model {
      SEDAN = 'SEDAN',
      MERCEDES = 'MERCEDES',
      CITROEN = 'CITROEN',
      SUZUKI = 'SUZUKI',
    }
    
    interface CarModelPrice {
      model :  Model;
      price : number;
    }
    
    const sedan: CarModelPrice = {
      model: Model.SEDAN,
      price: 25
    };
    
    const mercedes: CarModelPrice = {
      model: Model.MERCEDES,
      price: 20
    };
    
    const citroen: CarModelPrice = {
      model: Model.CITROEN,
      price: 15
    };
    
    const suzuki: CarModelPrice = {
      model: Model.SUZUKI,
      price: 30
    };

    let carModelPriceArr : CarModelPrice[] = [ sedan, mercedes, citroen, suzuki ];
    
    
    console.log(carModelPriceArr);

[{"model":"SEDAN","price":25},{"model":"MERCEDES","price":20},{"model":"CITROEN","price":15},{"model":"SUZUKI","price":30}]

up on sorting carModelPriceArr i would expect the following result.

[{"model":"SEDAN","price":25},{"model":"CITROEN","price":15},{"model":"SUZUKI","price":30},{"model":"MERCEDES","price":20}]

How can i do the custom sorting on the array carModelPriceArr?

following is the typescript playground for this https://stackblitz.com/edit/typescript-4zvofc

appreciate if you can help thank you

You could define a priority level as a number for every model, then sort like this:

 const cars = [{"model":"SEDAN","price":25},{"model":"MERCEDES","price":20},{"model":"CITROEN","price":15},{"model":"SUZUKI","price":30}]; const priority = { SEDAN: 1, CITROEN: 2, SUZUKI: 3, MERCEDES: 4 } const result = cars.sort(({ model: modelA }, { model: modelB }) => priority[modelA] - priority[modelB]); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM