Cas
Cas

Reputation: 174

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

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?

Upvotes: 0

Views: 73

Answers (2)

trincot
trincot

Reputation: 351369

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

Upvotes: 1

nem0z
nem0z

Reputation: 1123

Instead of get max value, you can sort by value then slice the array to get the top 10

First line juste populate te array with random data for exemple :

const getRandomInt = max => Math.floor(Math.random() * max);

const entries = Array(50).fill({})
    .map((x, i) => ({questionId: i, delta: getRandomInt(15)}));

const top10 = entries.sort((a, b) => b.delta - a.delta).slice(0, 10);
console.log(top10);

Upvotes: 1

Related Questions