首页 > 解决方案 > 如何根据给定值在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;

}

这可以重构吗?

标签: javascriptarraysreactjs

解决方案


逻辑解决方案:

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 

工作演示(在复制粘贴之前尝试自己解决)


推荐阅读