Cho mảng đối tượng xe hơi:
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' }];Sắp xếp mảng để các đối tượng cùng type nằm gần nhau.
Sắp xếp theo type theo thứ tự chữ cái.
Ví dụ
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);Kết quả
Đầu ra console:
[ { 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' } ]