Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

71
Views
Mapping through array of objects after filtering and displaying dynamic common property as a header

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. I would ideally like to avoid doing this several times especially given the class property is dynamic (not known before hand).

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.

I guess this question is about getting the right data structure so I can then map through it to display what I need, rather than simply sorting the array.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Use reduce method to do the group by operation and use Object.entries to get the list of items to iterate.

Try like this

{
    Object.entries(
        students.reduce((prevValue, currValue) => {
            prevValue[currValue.class]
                ? prevValue[currValue.class].push(currValue.name)
                : (prevValue[currValue.class] = [currValue.name]);
            return prevValue;
        }, {})
    ).map(([classs, names]) => `Class ${classs}: ${names.join(", ")}`);
}

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

    return (
        <div>
            {Object.entries(
                students.reduce((prevValue, currValue) => {
                    prevValue[currValue.class]
                        ? prevValue[currValue.class].push(currValue.name)
                        : (prevValue[currValue.class] = [currValue.name]);
                    return prevValue;
                }, {})
            ).map(([classs, names]) => (
                <div>{`Class ${classs}: ${names.join(", ")}`}</div>
            ))}
        </div>
    );
}

ReactDOM.render(<App />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

JS Fiddle => https://jsfiddle.net/9ahtz2jd/11/

NOTE: Always try to use filter, map, reduce functions.

enter image description here

about 4 years ago · Juan Pablo Isaza Report

0

let classes = {};

for(let student of students) {
  classes[student.class] = [...classes[student.class] || [], student.name];
}

console.log(classes);
about 4 years ago · Juan Pablo Isaza Report

0

You could create a new object with the name of the classes as keys and an array with the names of the students as values.

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

let klasses = {};

for (let i = 0; i < students.length; i++) {
  let student = students[i];
  let klass = student.class;

  if (!klasses[klass]) {
    klasses[klass] = [student.name];
  } else {
    klasses[klass].push(student.name);
  }
}

console.log(klasses);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!