I have an array made up of objects. Each object has two properties: name, value.
array = [
{
name: 'name1',
value: 0
},
{
name: 'name2',
value: 2
},
{
name: 'name3',
value: 4
},
{
name: 'name4',
value: 4
},
{
name: 'name5',
value: 3
},
{
name: 'name6',
value: 2
},
{
name: 'name7',
value: 0
},
{
name: 'name8',
value: 1
},
...
]
How do I get objects with the highest value property?
In the above example I should restitute objects that have value = 4
, value = 3
, value = 2
(i.e. the first 3 largest values)
i have tried something like this:
let first: 0
let second: 0
let third: 0
array.map((res: any) => {
if (res.value > first) {
third = second
second = first
first = res
} else if (res.value > second) {
third = second
second = res
} else if (res.value > third) {
third = res
}
})
The problem is that if there are two or more objects with the same value, it does not return them both, but only one.