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

groupby and select max id from object in react native

How to groupby and select max id from object in react native.
that was just a dummy data to explain you that how my object look like

[
 {"name": "alex", "subject": "english" "student_id": "1"},
 {"name": "hales", "subject": "science" "student_id": "2"},
 {"name": "joss", "subject": "english" "student_id": "3"},
 {"name": "alexandra", "subject": "science" "student_id": "4"},
 {"name": "mark", "subject": "math" "student_id": "5"},
]

First of all I want to group by subject and then select the student with max id so my output should look like that

[
 {"name": "joss", "subject": "english" "student_id": "3"},
 {"name": "alexandra", "subject": "science" "student_id": "4"},
 {"name": "mark", "subject": "math" "student_id": "5"},
]

What I have tried So far is that

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

const result = myobject.reduce(function (r, a) {
      r[a.case_id] = r[a.case_id] || [];
      r[a.case_id].push(a);
      return r;
    }, Object.create(null));

with above code I can group by but not able to get the max id so how could I achieve that?

>Solution :

You could group by subject and replace the value if student_id is greater.

As result take the values from the object.

const
    data = [{ name: "alex", subject: "english", student_id: "1" }, { name: "hales", subject: "science", student_id: "2" }, { name: "joss", subject: "english", student_id: "3" }, { name: "alexandra", subject: "science", student_id: "4" }, { name: "mark", subject: "math", student_id: "5" }],
    result = Object.values(data.reduce((r, o) => {
        if (!r[o.subject] || +r[o.subject].student_id < +o.student_id) {
            r[o.subject] = o;
        }
        return r;
    }, Object.create(null)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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