Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

객체 속성 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 속성 값이 같은 모든 개체가 함께 나타나도록 개체를 그룹화하는 프로그램을 작성해야 합니다.

객체가 types 속성의 알파벳순으로 정렬되도록 단순히 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' }
]