-2

i have a array like here

    let array = [
  {
    yearBirth : 1995,
    name : 'daniel',
  },
  {
    yearBirth : 1995,
    name : 'avi',
  },
  {
    yearBirth : 1993,
    name : 'john',
  },
  {
    yearBirth : 1993,
    name : 'david',
  },
]

How do I make it something like that?

{yearBirth : [
      {1995 : [{name : 'daniel'},{name : 'avi'}]},
      {1993 : [{name : 'john'},{name : 'david'}]}
    ]}

I tried to do it in a few ways I also looked for solutions here I did not find ... I would love a solution, thanks

Wyck
  • 10,311
  • 6
  • 39
  • 60
  • 1
    we would like to help you if you show us what you've tried!? – XMehdi01 Jul 11 '22 at 18:31
  • I tried to make a map and the map has to filter and it did not really work for me and I am looking for another solution. – danielmax123 Jul 11 '22 at 18:33
  • It's not clear what you'd be filtering (or why the `yearBirth` property is an array instead of an object keyed by the year, each value being an array of the names). – Dave Newton Jul 11 '22 at 18:40

1 Answers1

0

You could use reduce to group by yearBirth property,
then put it result in property yearBirth as an array:

let array = [{
    yearBirth: 1995,
    name: "daniel",
  },
  {
    yearBirth: 1995,
    name: "avi",
  },
  {
    yearBirth: 1993,
    name: "john",
  },
  {
    yearBirth: 1993,
    name: "david",
  },
];
const grouped = array.reduce(function (acc, val) {
    (acc[val.yearBirth] = acc[val.yearBirth] || []).push(val);
    return acc;
}, {});

let output = {
    yearBirth: [grouped]
}
console.log(output);

if you don't get the part of grouping there's a utility library called underscorejs with method groupBy

const grouped = _.groupBy(array, "yearBirth");

Also there are other methods to groupby on an array of objects without third-party library see

XMehdi01
  • 5,538
  • 2
  • 10
  • 34