0

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?

3
  • i'd say use a loop that breaks when no elements are left or 10 is reached , each time you find a value store it and delete it from the array and go again Commented Aug 1, 2022 at 14:42
  • Please visit help center, take tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output, preferably in a Stacksnippet Commented Aug 1, 2022 at 14:42
  • 3
    Since the size of the array is tiny, just sort it with a custom comparator and then take the first ten. Commented Aug 1, 2022 at 14:44

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.