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

JavaScript​ program that​ displays​ a list​ of​ names​ according​ to​ ​the sports​ group

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

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

expected output

// Chess:​ ​ [‘Ravindra’] }, { Cricket:​ [‘Ravindra’,'Ravi'] }, { Football:​ ​ [‘Ravi’,​ ​ ‘Rishabh’] }, { Table-Tennis:​ ​ [‘Rishabh']}]

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

>Solution :

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

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)
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