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