0

I have this array of values as shown below

var jsonData = 
[{date:'Jan 2004',volume:22088000},{date:'Feb 2004',volume:22088000},    
{date:'Mar 2004',volume:22088000},{date:'Apr 2004',volume:22088000},
{date:'May 2004',volume:22088000},{date:'Jun 2004',volume:22088000},
{date:'July 2004',volume:22088000},{date:'Aug 2004',volume:22088000},
{date:'Sept 2004',volume:22088000},{date:'October 2004',volume:22088000},
{date:'November 2004',volume:22088000},{date:'Dec 2004',volume:22088000}]

I have two Date Pickers (To Date and From Date ) in which i will pass this date value, for example (Jan 2004 and November 2004)

and on submit button , i want to collect the volume Data in between them

var volumeData = [];
// I don't know how to write a condition 
priceData.push([i, jsonData[i].volume]);

How can i do that ?

any ideas please ?

3 Answers 3

1

why overcomplicate things:

var volumeData = [], l = jsonData.length;
while (l--) {
    var d = Date.parse(jsonData[l].date);
    if (d >= startdate && d <= endate) { 
        volumeData.push(jsonData[l].volume) 
    };
} 
Sign up to request clarification or add additional context in comments.

Comments

0

First, you need to put your dates into a standard numeric format, not a human readable one.

Use (for example) the datejs library to do the conversion, or just use yyyymm instead.

Once you've done that, the rest should be obvious. Only convert back to human readable format at the last possible moment.

Comments

0

Edit - Ignore this answer: use @herostwist's answer; it's much simpler :)

There are a few stages to this:

To make things easier, you need to sort the data so we can extract a subset. Unfortunately, doing a naive sort by date will order them alphabetically, so we need to convert the date labels into something useful - i.e. numerical. (Note, Date.parse

for(var i=0, len=jsonData.length; i<len; i++) {
  jsonData[i].date = Date.parse(jsonData[i].date);
}

Then we can sort the data array:

jsonData.sort(function(a, b) {
  return a.date < b.date ? -1 : 1;
});

Then iterate through the array until you find the first instance of the lower bound:

var lower = Date.parse('Jan 2004'),
    lower_index = -1;

for(var i=0, len=jsonData.length; i<len; i++) {
  if(jsonData[i].date === lower) {
    lower_index = i;
    break;
  }
}

And the last instance of the upper bound:

var upper = Date.parse('November 2004'),
    upper_index = -1;

for(var i=0, len=jsonData.length; i<len; i++) {
  if(jsonData[i].date === upper) {
    upper_index = i;
  }
}

Then you can take a slice of the original data and construct your subset:

var data = jsonData.slice(lower, upper+1),
    volumeData = [];

for(var i=0, len=jsonData.length; i<len; i++) {
  volumeData.push([i, data[i].volume]);
}

Comments

Your Answer

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