I am trying to find a solution with my task for several hours straight without real improvements, so I will try to seek help from you.
Let's say, we have an array with values.
let values = [1000, 2000, 3000, 4000, 5000];
let maxValue = Math.max(...values);
let minValue = Math.min(...values);
values.map((item) => ((item) / maxValue));
As you can see, we are receiving [0.2, 0.4, 0.6, 0.8, 1], but what I want is to receive array like [0, 0.25, 0.5, 0.75, 1] out of it.
My logic is kinda shocked with this challenge, so I hope you could help me. I tried to set first value to 0 and last value to 1, but still nothing. Tried, to play with (item-minValue) / maxValue also, we are receiving first value as a 0, but it doesn't help.
Please take a look at following code which focusses on finding a value that can be added to output array [0, 0.2, 0.4, 0.6, 0.8] to make it [0, 0.25, 0.5, 0.75, 1]. Also it will always work on sorted arrays.
let values = [1000, 2000, 3000, 4000, 5000];
let maxValue = Math.max(...values);
let minValue = Math.min(...values);
const fractionsArr = values.map((item) => ((item-minValue) / maxValue));
const coefficient = (1 -fractionsArr[fractionsArr.length-1]) / (fractionsArr.length - 1)
return fractionsArr.map((item, index) => item + index * coefficient);
OR
let values = [1000, 2000, 3000, 4000, 5000];
let maxValue = Math.max(...values);
let minValue = Math.min(...values);
return values.map((item) => ((item-minValue) / (maxValue - minValue)));
You need to subtract the minValue
from both item
and maxValue
when mapping the values:
let values = [1000, 2000, 3000, 4000, 5000];
let maxValue = Math.max(...values);
let minValue = Math.min(...values);
values.map((item) => ((item - minValue) / (maxValue - minValue)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.