Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

javascript - Identify in which range a given number falls in array of object

I have an array of objects like

const score_card = [
        { "range":"0.6-1.5", "point":"10"},
        { "range":"1.6-2.5", "point":"20"},
        { "range":"2.6-3.5", "point":"30"},
        { "range":"3.6-4.5", "point":"40"},
        { "range":"4.6+", "point":"50"}
    ]    

Now if I receive a number 1.7 then I need to find out that in which range it falls, so in my example it falls in 1.6-2.5 and associated points for it is 20.

Since the score_card array will be the same all the time, I have used switch case as follows:

let number = 1.7

switch(number) {
   case (number>=0.6 || number<=1.5):
             console.log('points : 10')
             break;
   case (number>=1.6 || number <=2.5):
            console.log('points : 20')
              break;
   case (number >=2.6 || number <=3.5):
            console.log('points : 30')
             break;
   case (number>=3.6 || number<=4.5):
            console.log('points : 40')
             break;
   case (number>=4.6):
             console.log('points : 50')
             break;
   default:
        console.log('none')
                  
}    

Now the problem is the number (in our example 1.7) which we have passed in switch case is a part of an array and this switch case is written inside loop to get number one by one.Which makes code longer and possibly slower And I have to do this 4 more time for different cases. So can anyone help me and suggest me a way to handle this efficiently?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to make changes for your last last condition/range

const score_card = [
    { "range": "0.6-1.5", "point": "10" },
    { "range": "1.6-2.5", "point": "20" },
    { "range": "2.6-3.5", "point": "30" },
    { "range": "3.6-4.5", "point": "40" },
    { "range": "4.6+", "point": "50" }
]

const getPoints = score => {
    let points = 0;
    score_card.some(slab => {
        let [low, high] = slab.range.split('-');
        if (score >= +low && score <= +high) points = +slab.point;
    })
    return points;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...