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}
]
},
]
CodePudding user response:
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)
CodePudding user response:
let a = [
{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}
];
let c = []
a.forEach(e => {
const obj = {}
if(!c.some(item => item[e.year])){
obj[e.year] = a.filter(item => item.year == e.year)
c.push(obj)
}
})
console.log(c)