0

Given below is an array of objects, need to create sub-array in it with common make key, also all sub-array and main array needs to be sorted as follows:

  1. the main array to be sorted on make key alphabetically.
  2. sub-arrays to be sorted ASC on the basis of the year.

Input Array:

const cars = [
 {
 "make": "audi",
 "model": "r8",
 "year": "2006"
 }, {
 "make": "audi",
 "model": "s5",
 "year": "2005"
 }, {
 "make": "ford",
 "model": "mustang",
 "year": "2012"
 }, {
 "make": "ford",
 "model": "fusion",
 "year": "2015"
 }, {
 "make": "kia",
 "model": "optima",
 "year": "2012"
 },
];

Desired Array:

const cars = [
 {
 "make": "audi",
 "list": [
 {
 "model": "s5",
 "year": "2005",
 },
 {
 "model": "r8",
 "year": "2006",
 },
 ],
 },
 {
 "make": "ford",
 "list": [
 {
 "model": "mustang",
 "year": "2012",
 },
 {
 "model": "fusion",
 "year": "2015",
 },
 ],
 },
 {
 "make": "kia",
 "list": [
 {
 "model": "optima",
 "year": "2012",
 },
 ],
 },
 ];

What I have tried yet:

let filteredData = [];
cars.forEach((value)=>{
 var foundIndex = filteredData.findIndex( car => car.make === value.make );
 if(foundIndex != -1){
 let carData = filteredData[foundIndex];
 const {list} = carData;
 let nextObj = {'model': value.model, 'year': value.year};
 const newData = [...list, nextObj];
 carData['list'] = newData;
 filteredData[foundIndex] = carData;
 }else{
 
 let values = {'model': value.model, 'year': value.year}; 
 let data = [values];
 let obj = {'make':value.make, 'list': data};
 filteredData.push(obj);
 }
});
const sortedCars = filteredData.sort((a, b) => a.make.localeCompare(b.make));

Any optimal solution for this to make it better is welcomed.

asked Jan 12, 2022 at 1:24

2 Answers 2

0

This is really just a 'group by' with sorting. To avoid having to sort multiple nested arrays in the result you can sort (a copy) of the array by year before grouping, and then sort the result by make afterwards. Here using a for...of loop grouping into an object and then sorting the Object.values() as the result.

const cars = [
 { make: 'ford', model: 'fusion', year: '2015' },
 { make: 'audi', model: 'r8', year: '2006' },
 { make: 'audi', model: 's5', year: '2005' },
 { make: 'ford', model: 'mustang', year: '2012' },
 { make: 'kia', model: 'optima', year: '2012' },
];
const grouped = {};
for (const { make, ...rest } of [...cars].sort((a, b) => a.year - b.year)) {
 (grouped[make] ??= { make, list: [] }).list.push({ ...rest });
}
const result = Object.values(grouped).sort((a, b) =>
 a.make.localeCompare(b.make)
);
console.log(result);

Alternatively, because javascript objects sort integer properties by default you can 'group by' year within each list and then map the resulting object values to arrays. The outer array will need to be sorted explicitly.

const cars = [
 { make: 'ford', model: 'fusion', year: '2015' },
 { make: 'audi', model: 'r8', year: '2006' },
 { make: 'audi', model: 's5', year: '2005' },
 { make: 'ford', model: 'mustang', year: '2012' },
 { make: 'kia', model: 'optima', year: '2012' },
];
const result = Object.values(
 cars.reduce((a, { make, year, ...rest }) => {
 a[make] ??= { make, list: {} };
 a[make].list[year] ??= [];
 a[make].list[year].push({ year, ...rest });
 return a;
 }, {}))
 .map(({ make, list }) => ({ make, list: Object.values(list).flat() }))
 .sort((a, b) => a.make.localeCompare(b.make));
console.log(result);

answered Jan 12, 2022 at 1:45
Sign up to request clarification or add additional context in comments.

Comments

0
let filteredData = [];
cars.forEach((value)=>{
 var foundIndex = filteredData.findIndex( car => car.make === value.make );
 if(foundIndex != -1){
 let carData = filteredData[foundIndex];
 const {list} = carData;
 let nextObj = {'model': value.model, 'year': value.year};
 let newData = [...list, nextObj];
 
 newData.sort((a, b) => a.year.localeCompare(b.year));
 carData['list'] = newData;
 filteredData[foundIndex] = carData;
 }else{
 
 let values = {'model': value.model, 'year': value.year}; 
 let data = [values];
 let obj = {'make':value.make, 'list': data};
 filteredData.push(obj);
 }
});
const sortedCars = filteredData.sort((a, b) => a.make.localeCompare(b.make));
answered Jan 12, 2022 at 1:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.