ParseFloat array values - javascript

I'm trying to parse the values in my array then add them to a chart. Problem is I'm getting some unexpected numbers on the out put. I loop through and populate my array. On the button click I loop through and parse the data and put it into another array to pass to a chart series. This in theory works but the data points received are in accurate. I've attached a picture of what the console out puts look like. Once I parse it either i'm getting the first digit of the element or half of the number.
Thank you
Here is the code :
var testData = [];
for (var i = 0; i < 5; i++) {
testData[i] = populationData[i].Census;
console.log(testData[i]);
}
// the button action
$('#button').click(function () {
var mySeries = [];
var data = [];
for (var i = 0; i < 5; i++) {
data[i] = parseFloat(testData[i]);
mySeries[i] = data[i];
}
console.log(mySeries);
var chart = $('#container').highcharts();
chart.series[0].setData(mySeries);

You need to remove the commas - JavaScript does not use thousand separators
parseFloat(testData[i].replace(/,/g,""));
or just
parseInt(testData[i].replace(/,/g,""),10);
if there are no decimals

Related

FOR loop and Array issue

I'm using Adobe Livecycle Designer ES4 to create some report. Based on XML a try to fill table. I have problem with Array. I push data into array in for loop. Below examples of my code:
Results - blank textbox
var print_data = xfa.record.containerPrintingData;
var sfcArray = [];
for (var i = 0; i < 10; i++) {
sfc = print_data.resolveNode("sfcPrintingData["+ i +"]").sfc.value;
sfcArray.push(sfc);
};
this.rawValue = sfcArray.toString();
Results - get all items
var print_data = xfa.record.containerPrintingData;
var sfcArray = [];
for (var i = 0; i < 10; i++) {
sfc = print_data.resolveNode("sfcPrintingData["+ i +"]").sfc.value;
sfcArray.push(sfc);
this.rawValue = sfcArray.toString();
}
Results - get 2nd item x 10
var print_data = xfa.record.containerPrintingData;
var sfcArray = [];
for (var i = 0; i < 10; i++) {
sfc = print_data.resolveNode("sfcPrintingData[1]").sfc.value;
sfcArray.push(sfc);
this.rawValue = sfcArray.toString();
}
Why 1st example don't work and 2nd work correct? I need use this array in another loops. How to solve it?
Because, If it has 2 items, and you looping it for 10.
What happends is, when this.rawValue = sfcArray.toString(); is inside the loop, this.rawValue gets updated 2 times. First time One item will be there. second time 2 items.
For the next iteration there is no 3rd item. So code breaks with error. But this.rawValue still have 2 items.
Where as, when this.rawValue = sfcArray.toString(); is outside the loop, the code breaks with error and this.rawValue don't have any items in it.

Pass array values to another array

I have an array of input fields called '$inputFieldsArray' then I slice them to group by 3 into 'newArray' then I need new array value for each item to assign to another array cause in the end I need an array with input fields values grouped by 3. The end goal is to get an array which contains for 9 input fields ex [[i1,i2,i3],[i4,i5,i6],[i7,i8,i9]].
For some reason 'stringArray' output is nothing, first two arrays print correct results. It's probably some mistake I do regarding JS arrays.. Sorry js is not my main language, I try to learn it. Thanks.
Here is a screenshoot with chrome console:
Here is my function:
$($submitButton).click(function () {
// Get number of input fields
let $total = $("input[name^='bodyHeader']").length;
// Get input fields as objects
let $inputFieldsArray = $("input[name^='bodyHeader']");
let newArray = [];
let stringArray = [];
let j = 0;
// Group input fields by 3
for (let i = 0; i < $total - 1; i += 3) {
newArray[j] = $inputFieldsArray.slice(i, i + 3);
j++;
}
// Extract string values from newArray and pass them into stringArray
for (let k = 0; k < newArray.length - 1; k++) {
stringArray[k][0] = newArray[k][0].value;
stringArray[k][1] = newArray[k][1].value;
stringArray[k][2] = newArray[k][2].value;
}
// Print to test results
console.log($inputFieldsArray);
console.log(newArray);
console.log("String Array: " + stringArray);
... // Function logic is not complete
});
SOLUTION:
There is no way to declare dynamic length bidimensional array in js. Use this approach suggested by #Stephan :
stringArray[k] = [newArray[k][0].value, newArray[k][1].value,
newArray[k[2].value];
or this approach suggested by #Lorenzo Gangi:
var matrix = [],
cols = 3;
//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
matrix[i] = [];
}
stringArray[k] is undefined because you defined stringArray as [] (Your browser probably threw an exception). Additionally newArray[k] starts at index 0.
You could write stringArray[k] = [newArray[k][0].value, newArray[k][1].value, newArray[k][2].value] instead.
Basically,
stringArray[k]
is undefined yet, therefore setting its [0] property wont work. May do:
stringArray[k] =newArray[k].map(el=>el.value);
Alltogether:
$($submitButton).click(function () {
let stringArray = $("input[name^='bodyHeader']").toArray().reduce((res,_,i,arr)=>((i%3==0 && res.push(arr.slice(i,i+3).map(e=>e.value))),res),[]);
});

Auto increment row and column results to csv file in javascript

I'm converting XML results to CSV using the following code. It will automatically increment the 'row' but I am having to set each 'column' value. I attempted to alter the code but the outcome was not functional. I believe the issue lies within the 'new XML' line but I haven't been able to find any information relating to this. So my question is can how can this be coded to auto increment the column value as well?'
Thank you - Matt
var length = msg['result'].length();
var x = 0;
for(var i=0;i<length;i++)
{
tmp['row'][x] = new XML("<row/>");
tmp['row'][x]['column1'] = '"'+msg['result'][i]['this'].toString()+'"';
tmp['row'][x]['column2'] = '"'+msg['result'][i]['that'].toString()+'"';
tmp['row'][x]['column3'] = '"'+msg['result'][i]['other'].toString()+'"';
x++;
}
So after some more testing and guesswork, I came up with the following that is fucntional and returns the output I am needing:
var length = msg['result'].length();
var x = 0;
// This is the number of columns I know will be returned
var z = 3;
for(var i=0;i<length;i++)
{
tmp['row'][x] = new XML("<row/>");
tmp['column'][z] = new XML("<column/>");
tmp['row'][x]['column'][z] = '"'+msg['result'][i]['this'].toString()+'"';
tmp['row'][x]['column'][z] = '"'+msg['result'][i]['that'].toString()+'"';
tmp['row'][x]['column'][z] = '"'+msg['result'][i]['other'].toString()+'"';
z++;
x++;
}

How to split and add individual values in a string?

In my javascript, I've an array named my_array holding values like 0121, 1201, 0012, 0202 etc.
Each individual digit in the string is of importance. So, in the above example, there are 4 values in one string. E.g. 0121 holds 0,1,2,1.
The values can also be longer too. E.g. 01221, 21021 etc. (This is holding 5 values)
I want to know of the easiest and most effective way to do the following:
Add the first digits of all the strings in the array my_array. E.g. 0+1+0+0 in the above example
Add the second digits (e.g. 1+2+0+2) and so on.
I can loop through the array and split the values, then
for(i=0; i<my_array.length; i++){
var another_array = my_array[i].split();
//Getting too complicated?
}
How can I do it effectively? Someone please guide me.
Something like this
var myArray = ["0121", "1201", "0012", "0202"];
var firstValSum = 0;
for(var i = 0; i < myArray.length; i++) {
var firstVal = myArray[i].split("");
firstValSum += parseInt(firstVal[0], 10);
}
console.log(firstValSum); //1
This could be wrapped into a function which takes parameters to make it dynamic. i.e pass in the array and which part of the string you want to add together.
EDIT - This is a neater way of achieving what you want - this code outputs the computed values in an array as you specified.
var myArray = ["0121", "1201", "0012", "0202"];
var newArr = [];
for(var i = 0; i < myArray.length; i++) {
var vals = myArray[i].split("");
for(var x = 0; x < vals.length; x++) {
var thisVal = parseInt(vals[x], 10);
( newArr[x] !== undefined ) ? newArr[x] = newArr[x] += thisVal : newArr.push(thisVal);
}
}
console.log(newArr); //[1, 5, 3, 6];
Fiddle here
var resultArray = new Array(); // This array will contain the sum.
var lengthEachString = my_array[0].length;
for(j=0; j<lengthEachString ; j++){ // if each element contains 4 elements then loop for 4 times.
for(i=0; i<my_array.length; i++){ // loop through each element and add the respective position digit.
var resultArray[j] = parseInt( my_array[i].charAt(j) ); // charAt function is used to get the nth position digit.
}
}

string occurrences in a string

I'm am working on a script to count the number of times a certain string (in this case, coordinates) occur in a string. I currently have the following:
if (game_data.mode == "incomings") {
var table = document.getElementById("incomings_table");
var rows = table.getElementsByTagName("tr");
var headers = rows[0].getElementsByTagName("th");
var allcoord = new Array(rows.length);
for (i = 1; i < rows.length - 1; i++) {
cells = rows[i].getElementsByTagName("td");
var contents = (cells[1].textContent);
contents = contents.split(/\(/);
contents = contents[contents.length - 1].split(/\)/)[0];
allcoord[i - 1] = contents
}}
So now I have my variable allcoords. If I alert this, it looks like this (depending on the number of coordinates there are on the page):
584|521,590|519,594|513,594|513,590|517,594|513,592|517,590|517,594|513,590|519,,
My goal is that, for each coordinate, it saves how many times that coordinate occurs on the page. I can't seem to figure out how to do so though, so any help would be much appreciated.
you can use regular expression like this
"124682895579215".match(/2/g).length;
It will give you the count of expression
So you can pick say first co-ordinate 584 while iterating then you can use the regular expression to check the count
and just additional information
You can use indexOf to check if string present
I would not handle this as strings. Like, the table, is an array of arrays and those strings you're looking for, are in fact coordinates. Soooo... I made a fiddle, but let's look at the code first.
// Let's have a type for the coordinates
function Coords(x, y) {
this.x = parseInt(x);
this.y = parseInt(y);
return this;
}
// So that we can extend the type as we need
Coords.prototype.CountMatches = function(arr){
// Counts how many times the given Coordinates occur in the given array
var count = 0;
for(var i = 0; i < arr.length; i++){
if (this.x === arr[i].x && this.y === arr[i].y) count++;
}
return count;
};
// Also, since we decided to handle coordinates
// let's have a method to convert a string to Coords.
String.prototype.ToCoords = function () {
var matches = this.match(/[(]{1}(\d+)[|]{1}(\d+)[)]{1}/);
var nums = [];
for (var i = 1; i < matches.length; i++) {
nums.push(matches[i]);
}
return new Coords(nums[0], nums[1]);
};
// Now that we have our types set, let's have an array to store all the coords
var allCoords = [];
// And some fake data for the 'table'
var rows = [
{ td: '04.shovel (633|455) C46' },
{ td: 'Fruits kata misdragingen (590|519)' },
{ td: 'monster magnet (665|506) C56' },
{ td: 'slayer (660|496) C46' },
{ td: 'Fruits kata misdragingen (590|517)' }
];
// Just like you did, we loop through the 'table'
for (var i = 0; i < rows.length; i++) {
var td = rows[i].td; //<-this would be your td text content
// Once we get the string from first td, we use String.prototype.ToCoords
// to convert it to type Coords
allCoords.push(td.ToCoords());
}
// Now we have all the data set up, so let's have one test coordinate
var testCoords = new Coords(660, 496);
// And we use the Coords.prototype.CountMatches on the allCoords array to get the count
var count = testCoords.CountMatches(allCoords);
// count = 1, since slayer is in there
Use the .indexOf() method and count every time it does not return -1, and on each increment pass the previous index value +1 as the new start parameter.
You can use the split method.
string.split('517,594').length-1 would return 2
(where string is '584|521,590|519,594|513,594|513,590|517,594|513,592|517,590|517,594|513,590|519')

Categories