javascript - 如何根据给定值在Javascript中分配动态范围值?
问题描述
这里我有一个值数组
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
但是这些范围值必须是动态的。基于数组中的最高值和最低值。
请帮我找出这个。提前致谢
我在函数 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
工作演示(在复制粘贴之前尝试自己解决)
推荐阅读
- reactjs - React.js 身份验证
- python - 为什么我需要在已经导入模块时显式导入模块?
- android - 带有工具的 Android Studio 中的错误:showIn="navigation_view"
- react-native - 当应用程序不在前台时访问 React Native Firebase 远程输入通知Open.results
- git - Git 本地环境重置
- php - 强制应用程序直接去服务器获取数据而不是(从磁盘缓存)
- javascript - 在 React 中合并两个状态数组
- windows - 在 Win2012r2 上启用 FIPS 140-2 并使用 powershell 验证合规性
- c# - Xamarin XAML 未绑定
- python - 如何从字符串python打印完全匹配的单词