Search code examples
javascriptecmascript-6ecmascript-5

Compare a variable with object and return element according to the value difference


Since I'm not that good in JS, I will appreciate help here...

I have this array:

segments = [
    { state: 33, color: "red" },
    { state: 66, color:"yellow" },
    { state: 100, color: "green" }
]

Three variables:

goal = 100
currentValue = 26
percentage = currentValue * 100 / goal

I'm trying to write a function that compare percentage and state in the object, and return the color that accompanies the state. For example:

If percentage is < 33, should return "red".

If percentage is in between 33 & 66, has to return "yelow".

If percentage is > 66 or > goal, has to return "green".

So far I have this, but it doesn't work:

defineChartColor = (currentActivity, goal) => segments.find(segments => segments.state > percentage).color

Solution

  • You need to check against state, not value of the object with <=. The equal sign is important to find exact values, like the last one of 100.

    var segments = [{ state: 33, color: "red" }, { state: 66, color:"yellow" }, { state: 100, color: "green" }],
        goal = 100,
        currentValue = 26,
        percentage = currentValue * 100 / goal,
        getColor = (percentage, goal) => segments.find(({ state }) => percentage === goal
            ? state === 100
            : percentage <= state 
        ).color;
    
    console.log(getColor(33, 100));
    console.log(getColor(66, 100));
    console.log(getColor(100, 100));
    console.log(getColor(20, 20));