I am working with an array that contains objects, each with two properties: name and 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
},
...
]
I am trying to retrieve the objects with the highest value property from this array. Specifically, I want to get the objects with value = 4
, value = 3
, and value = 2
(the top 3 values).
let firstValue = 0;
let secondValue = 0;
let thirdValue = 0;
array.map((obj) => {
if (obj.value > firstValue) {
thirdValue = secondValue;
secondValue = firstValue;
firstValue = obj.value;
} else if (obj.value > secondValue) {
thirdValue = secondValue;
secondValue = obj.value;
} else if (obj.value > thirdValue) {
thirdValue = obj.value;
}
})
The issue I'm facing is that when there are multiple objects with the same value, my current method only returns one of them instead of all.