-1
  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

jsBug
  • 348
  • 1
  • 9

1 Answers1

1

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; }
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
  • -Terry Lennox thank you very much really satisfied with your answer – jsBug Jan 28 '22 at 08:44
  • 1
    i know how to do with for loop but leads bit time to take convert, i really like your array.reducer answer thank you very much - Terry Lennox – jsBug Jan 28 '22 at 08:47