基於孩子物件屬性在 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 屬性對陣列進行排序,以便物件按照 type 屬性的字母順序對齊。

完成此操作的完整程式碼如下 −

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' }
]

更新日期: 09-Oct-2020

203 次觀看

開啟職業生涯

完成課程獲得認證

開始
廣告