0

I have been looking around StackOverflow and other forums and I can't seem to find a solution to this.

I am currently trying to find the top 5 elements in a nested array with the highest value, but I would like it to return the full element and not just the value.

Here is the array that I am trying to get the elements from.

var data = [{ a: "b", value: 12}, {a: "bb", value: 39 }, {a: "bb", value: 150 }, { a: "c", value: 15}, {a: "cc", value: 83 }, {a: "ccc", value: 12 }, { a: "d", value: 55}, {a: "dd", value: 9 }, {a: "dd", value: 1 }]

Here is an example of what I would like returned

[{a:"b",value:150},{a:"cc",value:83},{a:"d",value:55},{a:"bb",value:39},{a:"c",value:15}]

Any help is much appreciated:)

1 Answer 1

2

var data = [
  { a: 'b', value: 12 },
  { a: 'bb', value: 39 },
  { a: 'bb', value: 150 },
  { a: 'c', value: 15 },
  { a: 'cc', value: 83 },
  { a: 'ccc', value: 12 },
  { a: 'd', value: 55 },
  { a: 'dd', value: 9 },
  { a: 'dd', value: 1 }
];

const res = data.sort((a, b) => b.value - a.value).slice(0, 5);
console.log(res);

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

1 Comment

I'll check it in a few minutes and let you know if it works, thank you very much sir/ma'am. :)

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.