-2

Using vanilla JavaScript and without lodash, what is the most efficient way to group an array of objects by value in the following manner?

For example if the input data is:

const data = [{year: "2021", name: "Rick"}, {year: "2020", name: "Joe"}, {year: "2021", name: "Sam"}, {year: "2019", name: "Sally"}, {year: "2019", name: "Jess"}];

and the output data is:

const result = [{year: "2021", data: [{year: "2021", name: "Rick"}, {year: "2021", name: "Sam"}]}, {year: "2020", data: [{year: "2020", name: "Joe"}]}, {year: "2019", data: [{year: "2019", name: "Sally"}, {year: "2019", name: "Jess"}]}]

JaeLeeSo
  • 213
  • 1
  • 4
  • 10

1 Answers1

-2

You can use Array.reduce.

In the reducer function, check whether the new array contains an item with the same year property. If so, push the current item to that item's data property. Otherwise, construct the appropriate object and push it to the array.

const data = [{year: "2021", name: "Rick"}, {year: "2020", name: "Joe"}, {year: "2021", name: "Sam"}, {year: "2019", name: "Sally"}, {year: "2019", name: "Jess"}];

const result = data.reduce((a, b) => {
    const year = a.find(e => e.year == b.year);
    if (year) {
        year.data.push(b);
    } else {
        a.push({year: b.year, data: [b]})
    }
    return a;
}, [])

console.log(result)
Spectric
  • 30,714
  • 6
  • 20
  • 43