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

I want to convert This array to this object

const movies = [
  { name: "Escape from Pretoria", year: 2020 },
  { name: "Good Will Hunting", year: 1997 },
  { name: "The Matrix", year: 1999 },
  { name: "Tarzan", year: 1999 },
  { name: "Titanic", year: 1997 },
  { name: "The Imitation Game", year: 2014 },
];

to object like this

const x = {
  1997: ["Good will Hunting", "Titanic"],
  1999: ["The Matrix", "Tarazan"],
  2014: ["The Imitation Game"],
  2020: ["Escape from Pretoria"],
};

Using reduce() or another way .. thank you!

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 :

Here’s a solution using reduce

const movies = [
  { name: "Escape from Pretoria", year: 2020 },
  { name: "Good Will Hunting", year: 1997 },
  { name: "The Matrix", year: 1999 },
  { name: "Tarzan", year: 1999 },
  { name: "Titanic", year: 1997 },
  { name: "The Imitation Game", year: 2014 },
];

const result = movies.reduce((acc, curr) => {
  if (acc[curr.year]) acc[curr.year].push(curr.name)
  else acc[curr.year] = [curr.name]
  return acc
}, {})

console.log(result)
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