Home > front end >  Converting a string to an Array of datetime x and y values
Converting a string to an Array of datetime x and y values

Time:10-31

I'm working with HighCharts and trying to update the chart series. So far, everything works fine when I use;

chart.series[0].setData([Date.UTC(2022, 9, 29,14,54,52), 34.74],[Date.UTC(2022, 9, 29,15,24,52), 35.6]);

However, the real data comes as a string such as;

data = '[Date.UTC(2022, 9, 29,14,54,52), 34.74]^[Date.UTC(2022, 9, 29,15,24,52), 35.6]';

Since the setData() method requires an Array of DateTime x and y values, I have to convert the above string to an array, which might be simple but I can't really get it working... I tried two ways:

  1. using Array.from()

    v2 = '[Date.UTC(2022, 9, 29,14,54,52), 34.74]^[Date.UTC(2022, 9, 29,15,24,52), 35.6]'; line = v2.split('^'); data = Array.from(line);

  2. using push()

    v2 = '[Date.UTC(2022, 9, 29,14,54,52), 34.74]^[Date.UTC(2022, 9, 29,15,24,52), 35.6]'; line = v2.split('^'); data = [] data.push(line)

but neither ways worked for me...

Can please someone point me to the right way of getting the array from the string?

Thanks Gus

CodePudding user response:

the line array is fine. You should define line first by using var/let/const.

const v2 = '[Date.UTC(2022, 9, 29,14,54,52), 34.74]^[Date.UTC(2022, 9, 29,15,24,52), 35.6]';

const  line = v2.split('^');

CodePudding user response:

Try this code:

 var result = "";
  var arrayOfDate = [];
  var data = '[Date.UTC(2022, 9, 29,14,54,52), 34.74]^[Date.UTC(2022, 9, 29,15,24,52), 35.6]';

 var array = data.split('^');

for (let i = 0; i < array.length; i  ) {
 var arr = array[i].replace('[Date.UTC(','').replace(']','').replace(')','');

 var miniArray = arr.split(',');

 var dt = Date.UTC(miniArray[0], miniArray[1],miniArray[2],miniArray[3],miniArray[4],miniArray[5]);


  arrayOfDate.push(dt);
  arrayOfDate.push(miniArray[6]);
}

chart.series[0].setData([arrayOfDate[0], arrayOfDate[1]],[arrayOfDate[2], arrayOfDate[3]]);
  • Related