0

I have an array of objects:

  const students = [
    { name: 'Tom', class: "Blue" },
    { name: 'Pom', class: "Blue" },
    { name: 'Max', class: "Red" },
    { name: 'Alex', class: "Red" },
    { name: 'John', class: "Yellow" }
  ];

And I would like to group the return values by the class property, so I can achieve something similar to this in HTML:

Class Blue: Tom, Pom
Class Red: Max, Alex
Class Yellow: John

note: the class property should be displayed once as HTML mark-up which is the reason I don't think this helps at all..

How should I go about it? I can user filter() (like below) but this is rather silly.

const classRed = students.filter(student => student.class === "Red);
const classBlue = students.filter(student => student.class === "Blue);
...

I started this jsfiddle, but not sure how to deal with this object to display how I want it.

Christopher
  • 592
  • 9
  • 31
  • Made some changes to your fiddle snippet: https://jsfiddle.net/8o2dxhjk/4/ – smac89 Dec 06 '21 at 00:51
  • Thanks @smac89, that's what I am trying to avoid though, 3+ separate loops, as the class property would be dynamic so I won't know it or how many will I get in my object. – Christopher Dec 06 '21 at 09:21

0 Answers0