Compare data within an interval and draw rectangles accordingly I have an interval array like below: 

var interval = [[1], [1,3], [3,5], [5,7], [7,9], [9]];


I want to compare an input value say 1.5 with in the interval, and create an array drawData = [0,1,0,0,0]. To do this, i'm using a if loop like below:

            if(attr.freq &lt; interval[0]){
                freqData = [0,0,0,0,0];
            }
            if(attr.freq &gt;= interval[1][0] &amp;&amp; attr.freq &lt; interval[1][1]){
                freqData = [1,0,0,0,0];
            }
            if(attr.freq &gt;= interval[2][0] &amp;&amp; attr.freq &lt; interval[2][1]){
                freqData = [1,1,0,0,0];
            }
            if(attr.freq &gt;= interval[3][0] &amp;&amp; attr.freq &lt; interval[3][1]){
                freqData = [1,1,1,0,0];
            }
            if(attr.freq &gt;= interval[4][0] &amp;&amp; attr.freq &lt; interval[4][1]){
                freqData = [1,1,1,1,0];
            }
            if(attr.freq &gt;= interval[5]){
                freqData = [1,1,1,1,1];
            }


but the interval may change and I also want to know if there is a better way to to compare within the intervals.
This can be rewritten using a single map statement.

We just have normalize the data by making the first and last intervals consistent with the other intervals, which are defined by two points.  We use Infinity to do this.

The final solution will work with an arbitrary number of test intervals.

Rewrite:

function inIntervals(val, intervals) {
  var intervals = intervals.slice(0),    // this makes a copy, so we don't disturb the original array
      last      = intervals.length - 1;

  intervals[0]    = [-Infinity      , intervals[0]];  // here we normalize the first and last intervals
  intervals[last] = [intervals[last], Infinity    ];

  return intervals.map(x =&gt; val &gt;= x[0] &amp;&amp; val &lt; x[1] ? 1 : 0)
}

var test = [[1], [1,3], [3,5], [5,7], [7,9], [9]];
console.log(inIntervals(1.5, test)); 
// [ 0, 1, 0, 0, 0, 0 ]


Update

To transform from a single element array to the format in your example:

x = [1,3,5,7,9]
var first = [x[0]];
x = x.map((x,i,a) =&gt; a[i+1] === undefined ? [x] : [x, a[i+1]])
x = [first].concat(x);