# Compare data within an interval and draw rectangles accordingly

I have an interval array like below:

var interval = [, [1,3], [3,5], [5,7], [7,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 < interval){
freqData = [0,0,0,0,0];
}
if(attr.freq >= interval && attr.freq < interval){
freqData = [1,0,0,0,0];
}
if(attr.freq >= interval && attr.freq < interval){
freqData = [1,1,0,0,0];
}
if(attr.freq >= interval && attr.freq < interval){
freqData = [1,1,1,0,0];
}
if(attr.freq >= interval && attr.freq < interval){
freqData = [1,1,1,1,0];
}
if(attr.freq >= interval){
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.

• What's your ultimate goal? To create a bar chart? If so, this looks like a roundabout way to achieve that. – 200_success Mar 3 '16 at 21:46

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    = [-Infinity      , intervals];  // here we normalize the first and last intervals
intervals[last] = [intervals[last], Infinity    ];

return intervals.map(x => val >= x && val < x ? 1 : 0)
}

var test = [, [1,3], [3,5], [5,7], [7,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];
x = x.map((x,i,a) => a[i+1] === undefined ? [x] : [x, a[i+1]])
x = [first].concat(x);

• Thanks for the answer. if the interval is [1,3,5,7,9] then does map function still works? – beeCoder Mar 3 '16 at 22:12
• My answer assumes an array of intervals as in your example, where each interval is defined by 2 points (a start and end) -- with the exception of the first and last array elements, which are assumed to be single points (so we have to normalize them). – Jonah Mar 3 '16 at 22:14
• Yes, I understand that. so if the array has single entries such as [1,3,5,7,9] then how does interval less than 1 and between 1 and 3 work ? – beeCoder Mar 3 '16 at 22:15
• Sorry, I don't understand your question. The code would need to be changed completely to handle input which was just an array of single numbers. It's not hard, it just becomes a different question. – Jonah Mar 3 '16 at 22:17
• Oh okay. Thanks but could you please help me with the new array. I'm working with that and not able to get the solution. – beeCoder Mar 3 '16 at 22:19