Astolgic
Astolgic

Reputation: 13

Getting top 5 elements with highest value in nested array

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

Upvotes: 0

Views: 243

Answers (1)

michael
michael

Reputation: 4173

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

Upvotes: 2

Related Questions