Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare Array of Objects in Javascript

I’d like to make this array:

[
   {main: "material", value: "blend"}, 
   {main: "material", value: "synthetic"}, 
   {main: "style", value: "curl"}, 
   {main: "style", value: "bob"}, 
   {main: "material", value: "premium"}
]

to this:

{
 material: ["blend", "synthetic", "premium"], 
 style: ["curl", "bob"]
}

I used two "FOR" but it didn’t work out well:( Quite newbie in Javascript🥲

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use reduce to have that result

const data = [{
  main: "material",
  value: "blend"
}, {
  main: "material",
  value: "synthetic"
}, {
  main: "style",
  value: "curl"
}, {
  main: "style",
  value: "bob"
}, {
  main: "material",
  value: "premium"
}]

const finalResut = data.reduce((result, currentData) => {
  const {
    main,
    value
  } = currentData
  if (!result[main]) {
    result[main] = []
  }
  result[main].push(value)
  return result
}, {})

console.log(finalResut)
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading