基於物件屬性對 JavaScript 進行分組


我們有一組物件陣列,其中包含一些汽車的資料。陣列如下所示 -

const cars = [{
   company: 'Honda',
   type: 'SUV'
}, {
   company: 'Hyundai',
   type: 'Sedan'
}, {
   company: 'Suzuki',
   type: 'Sedan'
}, {
   company: 'Audi',
   type: 'Coupe'
}, {
   company: 'Tata',
   type: 'SUV'
}, {
   company: 'Morris Garage',
   type: 'Hatchback'
}, {
   company: 'Honda',
   type: 'SUV'
}, {
   company: 'Tata',
   type: 'Sedan'
}, {
   company: 'Honda',
   type: 'Hatchback'
}];

我們需要編寫一個程式來對物件進行分組,以便所有具有相同 type 屬性值的物件同時出現。

我們只需根據 type 屬性對陣列進行排序,以便物件按 types 屬性的字母順序對齊。

執行此操作的完整程式碼如下 -

示例

const cars = [{
   company: 'Honda',
   type: 'SUV'
}, {
   company: 'Hyundai',
   type: 'Sedan'
}, {
   company: 'Suzuki',
   type: 'Sedan'
}, {
   company: 'Audi',
   type: 'Coupe'
}, {
   company: 'Tata',
   type: 'SUV'
}, {
   company: 'Morris Garage',
   type: 'Hatchback'
}, {
   company: 'Honda',
   type: 'SUV'
}, {
   company: 'Tata',
   type: 'Sedan'
}, {
   company: 'Honda',
   type: 'Hatchback'
}];
   const sorter = (a, b) => {
      return a.type.toLowerCase() > b.type.toLowerCase() ? 1 : -1;
   }
   cars.sort(sorter);
console.log(cars);

輸出

控制檯中的輸出將為 -

[
   { company: 'Audi', type: 'Coupe' },{ company: 'Honda', type: 'Hatchback' },{ company: 'Morris Garage', type: 'Hatchback' },{ company: 'Tata', type: 'Sedan' },{ company: 'Suzuki', type: 'Sedan' },
   { company: 'Hyundai', type: 'Sedan' },{ company: 'Honda', type: 'SUV' },{ company: 'Tata', type: 'SUV' },{ company: 'Honda', type: 'SUV' }
]

更新時間: 19-Aug-2020

96 瀏覽次數

開啟您的職業生涯

完成課程取得認證

開始
廣告
© . All rights reserved.