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

Vue search array for unique "Years": string, and make a new array with each element being a unique Year object key

I’m currently attempting to create a new array of objects sorted by year. What would be the best way to loop through an array of objects that look like this:

[
     {id: 42, count: 250, month: "January", year: 2024}
     {id: 37, count: 2023, month: "January", year: 2023}
     {id: 1, count: 1111, month: "January", year: 2022}
     {id: 2, count: 100, month: "February", year: 2022}
     {id: 3, count: 500, month: "March", year: 2022}
     {id: 6, count: 1, month: "April", year: 2022}
     {id: 8, count: 500, month: "May", year: 2022}

];

And create a new array that would look like this:

[
     {
       2024: [{id: 42, count: 250, month: "January", year: 2024}]
     },
     {
       2023: [{id: 37, count: 2023, month: "January", year: 2023}]
     },
     {
       2022: [
              {id: 1, count: 1111, month: "January", year: 2022},
              {id: 2, count: 100, month: "February", year: 2022},
              {id: 3, count: 500, month: "March", year: 2022},
              {id: 6, count: 1, month: "April", year: 2022},
              {id: 8, count: 500, month: "May", year: 2022}
           ]
      },
]

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 :

One way with forEach and find:

const arr = [
     {id: 42, count: 250, month: "January", year: 2024},
     {id: 37, count: 2023, month: "January", year: 2023},
     {id: 1, count: 1111, month: "January", year: 2022},
     {id: 2, count: 100, month: "February", year: 2022},
     {id: 3, count: 500, month: "March", year: 2022},
     {id: 6, count: 1, month: "April", year: 2022},
     {id: 8, count: 500, month: "May", year: 2022}
]
const res = []
arr.forEach(a => {
  let ex = res.find(r => a.year in r)
  if(ex) {
    ex[a.year].push(a)
  } else res.push({[a.year]: [a]})
})
console.log(res)
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