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

Get multiple highest values from array of objects

I’ve got an array of objects:

[
  {
    questionId: 1,
    delta: 3,
  },
  {
    questionId: 3,
    delta: 11,
  },
  {
    questionId: 6,
    delta: 11,
  }
  ....
]

With up to 43 entries.

To get the entry with the highest delta out of this, I would do something like

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 maxDelta = Math.max.apply(Math, array.map(question=> {
    return question.delta;
}));

But now I need the 10 highest delta’s out of this array. How would I do that?

>Solution :

If the array were huge you’d probably look into a heap or selection-based algorithm, but as your array is tiny (with up to 43 elements), you can just sort it in descending order of delta:

const array = [{questionId: 1,delta: 3,},{questionId: 3,delta: 11,},{questionId: 6,delta: 11,},{questionId: 7,delta: 8,},{questionId: 8,delta: 6,},{questionId: 10,delta: 4,},{questionId: 12,delta: 7,},{questionId: 13,delta: 16,},{questionId: 16,delta: 2,},{questionId: 17,delta: 14,},{questionId: 18,delta: 12,},{questionId: 21,delta: 19,},{questionId: 23,delta: 5,}];
const result = array.sort((a, b) => b.delta - a.delta)
                    .slice(0, 10)
                    .map(a => a.delta);
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