基於物件屬性對 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' }
]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP