Home > database >  JavaScript​ program that​ displays​ a list​ of​ names​ according​ to​ ​the Subject​ group
JavaScript​ program that​ displays​ a list​ of​ names​ according​ to​ ​the Subject​ group

Time:07-15

let a = 
[
    {
        Name: 'Josh',
        Subject: ['Biology', 'Chemistry'],  
    },
    {
        Name: 'James',
        Subject: ['Chemistry', 'Physics'],
    },
    {
        Name: 'Mary',
        Subject: ['Physics', 'Mathematics'],
    },
]

const result = a.reduce((groupedSubject, person) => {
    const Subject = person.Subject
    if(groupedSubject[Subject]== null) groupedSubject[Subject] = []
    groupedSubject[Subject].push(person)
    return groupedSubject
}, {})
    console.log(result)

I was able to group according to the subject, but subject is an array. how do i group it by individual subjects?

CodePudding user response:

You need to iterate Sports array as well.

const
    data = [{ Name: 'Ravindra', Sports: ['Chess', 'Cricket'] }, { Name: 'Ravi', Sports: ['Cricket', 'Football'] }, { Name: 'Rishabh', Sports: ['Table-Tennis', 'Football'] }],
    result = data.reduce((groupedSports, person) => {
        person.Sports.forEach(sport => {
            groupedSports[sport] ??= [];
            groupedSports[sport].push(person.Name);
        })
        return groupedSports;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

You can iterate over all sports and check if it already exists, if not, spread all current entries and add the new persons Name to the array.

let a = [{
    Name: 'Ravindra',
    Sports: ['Chess', 'Cricket'],
  },
  {
    Name: 'Ravi',
    Sports: ['Cricket', 'Football'],
  },
  {
    Name: 'Rishabh',
    Sports: ['Table-Tennis', 'Football'],
  },
]

const result = a.reduce((groupedSports, person) => {
  person.Sports.forEach((sport) => {
    groupedSports[sport] = groupedSports?.[sport]
      ? [...groupedSports[sport], person.Name]
      : [person.Name];
  });
  return groupedSports;
}, {});

console.log(result)

  • Related