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