I have an array of objects that I want to find the highest value of the key ‘saving’. I’ve used this:
maxSaving = tableResults.reduce((prev, current)=> ( (prev.saving > current.saving) ? prev : current),0)
Which correctly gives me the highest result in the array. The issue I have is that it’s always the last instance of the highest result if there are multiple results for the highest number and I want the first, not the last.
I thought something like this would work but it doesn’t:
maxSaving = tableResults.reduce((prev, current)=> ( (prev.saving > current.saving && prev.saving != current.saving) ? prev : current),0)
I really can’t figure it out and I am new to using reduce.
4
Answers
I’m assuming that your array kinda looks like this.
In this code if you have 2 elements with the same highest value, the code will return only the first occurrence because
maxObject
value is only updated if the current value is higherIt seems like you’re on the right track with using the
reduce
function to find the maximum value in the array of objects based on the ‘saving’ key. To get the first occurrence of the highest value rather than the last, you might need to slightly adjust the logic.You can modify the
reduce
function to track both the maximum value and its index in the array. Here’s an example of how you could do this:This code snippet initializes the
reduce
function with an object that keeps track of both the maximum value found so far (maxValue
) and its index in the array (index
). It iterates through the array of objects, updating these values whenever a higher ‘saving’ value is encountered. Finally, it retrieves the object with the first occurrence of the highest ‘saving’ value using the index stored in themaxSaving
object.This way, you can get the first object that contains the highest ‘saving’ value within the array of objects.
This is one of those scenarios where you should not provide the initial value as second argument to
reduce
. Moreover, the value 0 is just wrong for such initial value, since the accumulator is assumed to be an object, not an integer.Apart from that you should just change
>
to>=
and you’re done.The trick is to make a change ONLY when
current.saving
is greater thanprev.saving
– this should prevent replacing the first match with the second and so on. So something like this should do it: