JavaScript 中根据子对象属性进行数组分组

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/17 1:48:17

我们有一个对象数组,其中包含一些汽车的数据。数组如下所示 −

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

相关文章


有用资源