[英]How to assign dynamic range values in Javascript based on given values?
這里我有一個值數組
let array = [4023,4545,34,34353,34,454,4523,234,4555,232,4353,444,1232,4542,565,7,345,3456,8908]
我需要將這些數組值拆分為 4 個動態范圍值。
For eg: 1 to 1000, 1000 to 2000, 3000 to 4000, 4000 to 5000
但是這些范圍值必須是動態的。 基於數組中的最高值和最低值。
請幫我找出這個。 提前致謝
我在 function updateColor [如果條件] 中有硬編碼值。
function updateColor() {
function updateColorValue(colorJsonObject, colorValue) {
const updatedProperties = { ...colorJsonObject.properties, color: colorValue };
colorJsonObject.properties = updatedProperties;
}
colorData.features.map((colorObject) => mapData?.data?.map((apiData) => {
if (colorObject.properties.name === apiData?.name) {
if (
apiData?.cumulativeMetric?.noOfProjects >= 1
&& apiData?.cumulativeMetric?.noOfProjects <= 1000
) {
updateColorValue(colorObject, 5);
} else if (
apiData?.cumulativeMetric?.noOfProjects >= 1000
&& apiData?.cumulativeMetric?.noOfProjects <= 6000
) {
updateColorValue(colorObject, 2);
} else if (
apiData?.cumulativeMetric?.noOfProjects >= 40000
&& apiData?.cumulativeMetric?.noOfProjects <= 50000
) {
updateColorValue(colorObject, 3);
}
}
}));
}
而不是這種硬編碼。 我需要使 if 條件動態化。
我做了這樣的事情來使動態:
export const GeneralFunction = (data) => {
let array = data.map(i => i?.latestMetric?.numberOfProjects || 0)
let min = Math.min.apply(null, array);
let Maximum = Math.max(...array)
let Minimum = Math.min.apply(null, array.filter(n => n !== min));
let range = (Maximum - Minimum) / 4
let FirstRange = [Minimum, Minimum + range]
let SecondRange = [FirstRange[1], FirstRange[1] + range]
let ThirdRange = [SecondRange[1], SecondRange[1] + range]
let FourthRange = [ThirdRange[1], ThirdRange[1] + range]
let Obj = {
firstRange: FirstRange,
secondRange: SecondRange,
thirdRange: ThirdRange,
fourthRange: FourthRange
}
return Obj;
}
這可以重構嗎?
邏輯解決方案:
1) find min and max from your array , lets say
min = 2000
max = 4000
2) now we have to create 4 range
(max-min)/no of range
(4000 - 2000)/4
= 500
3) create your range
First range = 2000 to 2000 + 500
Second range = 2000+500 to 2000+500+500
...
4) then loop through your array and compare in which range it belongs
工作演示(在復制粘貼之前嘗試自己解決)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.