0

So I am trying to find if a certain number is in between two other numbers.

I have an array of 'Bands' and their 'Color' codes.

What I want is, if the 'co2Amount' is in between one of the array 'Band' values, then it displays that bands 'Color' code.

So the code below should output '#c8ff5c' as its the color code for any co2 amount between 101 and 200.

Heres what I have:

var co2Bands = [ {Band:"0-100",Color:"#deff9e" }, {Band:"101-200",Color:"#c8ff5c"}, ]; 

var co2Amount = "150";

$.each(co2Bands, function() { 
var bandNumber = this.Band.split('-');
if (bandNumber[0] >= co2Amount && bandNumber[1] <= co2Amount) {
$('#co2ColorCode').append(this.Color+'<br>'); 
}
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="co2ColorCode"></div>

1
  • Do you have control of the object in the co2Bands array? If so I'd suggest splitting Band in to two separate integers, min and max Commented Jun 15, 2020 at 10:10

1 Answer 1

1

Some issues:

  • You need to convert the splits to number:

    this.Band.split('-').map(Number)
    
  • co2Amount should be a number too, not a string

  • your two conditions are both testing the wrong thing

var co2Bands = [ {Band:"0-100",Color:"#deff9e" }, {Band:"101-200",Color:"#c8ff5c"}, ]; 

var co2Amount = 150;

$.each(co2Bands, function() { 
  var bandNumber = this.Band.split('-').map(Number);
  if (bandNumber[0] <= co2Amount && co2Amount <= bandNumber[1]) {
    $('#co2ColorCode').append(this.Color+'<br>'); 
  }
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="co2ColorCode"></div>

Sign up to request clarification or add additional context in comments.

2 Comments

See other problems I have added to the answer. The snippet shows the color now.
you can use parseInt also to convert the string to number

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.