const mixedData = [{name :'Darci' , skill : 'python'},{name :'Darci' , skill : 'javascript'},{name :'Darci' , skill : 'react js'},{name :'Brooke' , skill : 'Photoshop'},{name :'Brooke' , skill : 'Indesign'},{name :'John' , skill : 'mangoDB'},{name :'john' , skill : 'mySQL'}]
but i want output like this
const Data = [{name: 'Darci' , skill : ['python' , 'javascript' , 'react js']},
{name: 'Brooke' , skill : ['Photoshop' , 'Indesign']},
{name: 'Jhon' , skill : ['mangoDB' , 'mySQL']},
]
but i dont want to hard code by filter method like below code
const finalArray = mixedData.filter(e=> e.name === 'Darci' ?{...} : {...}
)
no matter how may unique values in object filter please anyone help me out of this solution
You could also get the result using Array.reduce() to group the skills according to the user name:
const mixedData = [{name :'Darci' , skill : 'python'},{name :'Darci' , skill : 'javascript'},{name :'Darci' , skill : 'react js'},{name :'Brooke' , skill : 'Photoshop'},{name :'Brooke' , skill : 'Indesign'},{name :'John' , skill : 'mangoDB'},{name :'john' , skill : 'mySQL'}]
const result = Object.values(mixedData.reduce((acc, { name, skill }) => {
acc[name] ||= { name, skill: [] };
acc[name].skill.push(skill);
return acc;
}, {}));
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }