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:

var array = [
      {
        id: 1,
        value: 20,
      },
      {
        id: 2,
        value: 10,
      },
      {
        id: 3,
        value: 10,
      },
      {
        id: 4,
        value: 3,
      },
      {
        id: 5,
        value: 2,
      },
    ];

}]

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

Result

var newArray = [0, 1, 1, 2, 3]

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:

var array = [
      {
        id: 1,
        value: 20,
      },
      {
        id: 2,
        value: 10,
      },
      {
        id: 3,
        value: 10,
      },
      {
        id: 4,
        value: 3,
      },
      {
        id: 5,
        value: 2,
      },
    ];


const order = new Set(array.map(el => el.value))

const res = array.map(el => [...order].indexOf(el.value))

console.log(res)

in case you need to sort the array before:

var array = [
      {
        id: 1,
        value: 10,
      },
      {
        id: 2,
        value: 10,
      },
      {
        id: 3,
        value: 20,
      },
      {
        id: 4,
        value: 3,
      },
      {
        id: 5,
        value: 2,
      },
    ];

const sortedArray = array.sort((a,b) => a.value >= b.value ? -1 : 1)

const order = new Set(sortedArray.map(el => el.value))

const res = sortedArray.map(el => [...order].indexOf(el.value))

console.log(res)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement