I have an array sorted in ascending order in java script which contains dates in milliseconds.
// Sample data; This may grow upto 1k or 2k
var dates = [1333391400000,1335292200000,1335810600000,1336329000000,1336933800000,1337020200000,
1337193000000,1337538600000,1337625000000,1337797800000,1338316200000,1338921000000,
1339093800000,1339439400000,1340303400000,1341772200000,1342463400000,1343068200000];
I don't have start and end index. I have values. I need to get all dates between 2 dates (Min and Max) from the java script array. I am getting this array from Java through JSON.
Here is the method to get dates between min and max:
function getDatesBetweenRange(min,max){
var subArray = [];
var value, jCntr=0;
for(var iCntr=0;iCntr<dates.length;iCntr++){
value = dates[iCntr];
if(value>max)
break;
if(value >=min && value <=max){
subArray[jCntr++]= value;
}
}
return subArray;
}
As array is in ascending sorted order; I am breaking loop if I get max value than the provided max value in the argument.
Is there any other efficient way to get values from Java Script array ?
A Range object is created without parameters: let range = new Range(); Then we can set the selection boundaries using range. setStart(node, offset) and range.
JavaScript Range is a function that is supported by JavaScript in order to return all the integer and its value from starting to the ending while traversing from start index to the end index.
To check if a number is between two numbers: Use the && (and) operator to chain two conditions. In the first condition check that the number is greater than the lower range and in the second, that the number is lower than the higher range. If both conditions are met, the number is in the range.
Here's a semi binary filter method that seems more efficient (at least in my browsers - Chrome, Firefox, IE9)
function filterBinary(arr,min,max){
var len = arr.length
,up = -1
,down = len
,rrange= []
,mid = Math.floor(len/2)
;
while (up++<mid && down-->mid){
if (arr[up]>=max || arr[down]<=min){break;}
if (arr[up]>=min){
rrange.push(arr[up]);
}
if (arr[down]<=max){
rrange.push(arr[down]);
}
}
return rrange;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With