Skip to content
Advertisement

JavaScript – How to calculate the distance from max value in array of objects

I currently have a problems counting the distance between the max value and other values in array. Basically I want to make a new array where the values will be the distances from the max value. What I mean by this:

Example

I have an array of objects:

JavaScript

I want the result of this new algorithm that I am trying to make to be like this:

Result

JavaScript

Reason for this are the distance between the max value and other values that we have. The values that are same needs to have the same distance. Max value is 20 so it needs to have 0 as a result, 10 is second value and it is 1 distance away from max value and so on.

What should I do to start working on this?

Advertisement

Answer

In the case your array is already sorted:

JavaScript

in case you need to sort the array before:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement