I wanted to extract similar values from an array of objects and create a new array with it but in a different format. so I was able to do it but I think the code is a bit lengthy. sure there will be less code to do it. so anyone knows any other way to do it and maybe a proper way to do it? THANKS IN ADVANCE.
const data = [
{
id: 1,
type: 'easy',
name: 'type 1',
class: 12
},
{
id: 2,
type: 'easy',
name: 'type 2',
class: 10
},
{
id: 3,
type: 'medium',
name: 'type 3',
class: 12
},
{
id: 4,
type: 'hard',
name: 'type 4',
class: 10
},
{
id: 5,
type: 'medium',
name: 'type 5',
class: 10
},
{
id: 6,
type: 'easy',
name: 'type 2',
class: 10
},
{
id: 7,
type: 'medium',
name: 'type 3',
class: 12
},
{
id: 8,
type: 'hard',
name: 'type 4',
class: 10
},
{
id: 9,
type: 'medium',
name: 'type 5',
class: 10
},
{
id: 10,
type: 'hard',
name: 'type 4',
class: 10
},
]
const dataNeeded = [];
data.forEach(dataItem => {
if(dataNeeded.length) {
const isExist = dataNeeded.find(dataNeededItem => dataNeededItem.type === dataItem.type);
if(isExist) {
dataNeeded.forEach((dataNeededItem, index) => {
if(dataNeededItem.type === dataItem.type) {
dataNeeded[index].tests.push(dataItem)
}
})
} else {
dataNeeded.push({
type: dataItem.type,
tests: [dataItem]
})
}
} else {
dataNeeded.push({
type: dataItem.type,
tests: [dataItem]
})
}
})
console.log(dataNeeded);
CodePudding user response:
You can do the same thing pretty easily just by first using a Map
and then transforming that map into an array.
const data=[{id:1,type:'easy',name:'type 1',class:12},{id:2,type:'easy',name:'type 2',class:10},{id:3,type:'medium',name:'type 3',class:12},{id:4,type:'hard',name:'type 4',class:10},{id:5,type:'medium',name:'type 5',class:10},{id:6,type:'easy',name:'type 2',class:10},{id:7,type:'medium',name:'type 3',class:12},{id:8,type:'hard',name:'type 4',class:10},{id:9,type:'medium',name:'type 5',class:10},{id:10,type:'hard',name:'type 4',class:10}];
const map = new Map();
data.forEach((datum) => {
// add to map if it doesn't exist yet
if (!map.has(datum.type)) map.set(datum.type, []);
// push to the right type
map.get(datum.type).push(datum);
});
// transform map into array
const dataNeeded = Array.from(map).map(([type, tests]) => ({ type, tests }));
console.log(dataNeeded);