pushing into arrays in javascript - javascript

My script (is meant to) grab text from the a page (which works fine) and then splits it by by newline (\n) and puts each splitted string into an array called "dnaSequence"; from there it loops through each element in the array and if the string contains the character ">" it assigns that string to the "var header_name", else it pushes all other lines into a new array called "dnaSubseq". The original text looks something like this:
>header_1
gctagctagc
cgcgagcgagc
>header_2
gcgcatgcgac
When I execute the code it fails to alert on anything. Here is the code:
function loaderMy() {
var dnaSubseq = [];
var dnaSequence = [];
var header_name = "";
var splittedLines = document.getElementById("page-wrapper").innerText;
dnaSequence = splittedLines.split('\n');
for (var i = 0; i < dnaSequence.length; i++) {
if (dnaSequence[i].match(/>/)) {
header_name = dnaSequence[i];
alert(header_name);
}
else {
dnaSubseq.pushValues(dnaSequence[i]);
}
alert(dnaSubseq);
}
}

Change
dnaSubseq.pushValues(dnaSequence[i]);
To
dnaSubseq.push(dnaSequence[i]);

If it doesn't alert anything, that means you forgot to invoke the function :)
loaderMy();
http://jsfiddle.net/zszyg5qx/

Try this function
function loaderMy() {
var dnaSubseq = [];
var dnaSequence = [];
var header_name = "";
var splittedLines = document.getElementById("page-wrapper").innerText;
dnaSequence = splittedLines.split('\n');
for (var i = 0; i < dnaSequence.length; i++) {
if (dnaSequence[i].match(/>/)) {
header_name = dnaSequence[i];
alert(header_name);
}
else {
dnaSubseq.push(dnaSequence[i]);
}
alert(dnaSubseq);
}
}

Related

Unable to parse json using javascript

I have a json which i'm trying to parse it using javascript. Iteration count and the pages getting appended to it are going to be dynamic.
Expected Result
Just like the above image i'm able to take dynamic iteration keys from the below mentioned json.
Iteration.json
{
"count":[
{
"iteration1":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
},
{
"iteration2":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
}
]
}
When i click on iteration it has to populate the corresponding pagenames for that particular iteration as shown in expected result image. But what i get actually is (refer the image below):
Please find the code that i tried:
var pagenamearray = [];
$.getJSON("iteration.json", function(json) {
var hits = json.count;
var iterations, tnname, iteration;
for (var k in hits) {
var value;
if (hits.hasOwnProperty(k)) {
value = hits[k];
var iteratearray = [];
for (var j in value) {
if (value.hasOwnProperty(j)) {
j;
var check = value[j];
for (var i in check) {
if (check.hasOwnProperty(i)) {
var test = check[i];
for (var t in test) {
if (test.hasOwnProperty(t)) {
var pagename = JSON.stringify(t)
var arr = []
if (pagename.includes("PageName")) {
//alert("Key is " +pagename + ", value is" + JSON.stringify(test[t]));
for (var it = 0; it < hits.length; it++) {
if ((Object.keys(hits[it])).includes(j)) {
var pagenamevalue = test[t];
arr[it] = [];
arr.push(pagenamevalue);
}
}
}
//alert(arr)
}
pagenamearray.push(arr);
}
}
}
}
var row = document.createElement('div');
row.setAttribute("class", "row");
row.setAttribute("id", j)
var gridWidth = document.createElement('div');
gridWidth.setAttribute("class", "col-lg-12");
var panelRoot = document.createElement('div');
panelRoot.setAttribute("class", "panel panel-default");
var panelHeading = document.createElement('div');
panelHeading.setAttribute("class", "panel-heading");
var heading3 = document.createElement('a');
heading3.setAttribute("class", "panel-title");
var icon = document.createElement('i');
icon.setAttribute("class", "fa fa-long-arrow-right fa-fw");
heading3.appendChild(icon);
heading3.innerHTML = j;
heading3.setAttribute("onclick", "doit('" + j + "');");
panelHeading.appendChild(heading3);
/* var panelBody=document.createElement('div');
panelBody.setAttribute("class","panel-body");
panelBody.setAttribute("id","panellinks");*/
panelRoot.appendChild(panelHeading);
// panelRoot.appendChild(panelBody)
gridWidth.appendChild(panelRoot);
row.appendChild(gridWidth);
document.getElementById("analysis").appendChild(row);
}
}
}
});
function doit(value) {
var ul = document.getElementById(value);
if (ul != undefined) {
$("#" + "expandlinks").remove();
$("#" + value + value).remove();
}
var accordion = document.getElementById(value);
var panelBody = document.createElement('div');
panelBody.setAttribute("class", "panel-body");
panelBody.setAttribute("id", "expandlinks")
var tablediv = document.createElement('div')
var tablelink = document.createElement('a');
tablediv.appendChild(tablelink);
var graphdiv = document.createElement('div')
var graphlink = document.createElement('a');
graphdiv.appendChild(graphlink);
var recommndiv = document.createElement('div');
var recommendlink = document.createElement('a');
recommndiv.appendChild(recommendlink)
//alert(pagenamearray.length)
tablelink.innerHTML = pagenamearray;
/*graphlink.innerHTML="Timeline View";
recommendlink.innerHTML="Recommendations";*/
panelBody.appendChild(tablediv);
panelBody.appendChild(recommndiv);
panelBody.appendChild(graphdiv);
accordion.appendChild(panelBody);
}
Any advise on how to achieve this would be of great help. Thanks in advance.
I think the problem is how you assign the pagenamearray to tablelink.innerHTML. This converts the array to a string, converting all elements in the array to a string too and separating them by a comma each. However, your pagenamearray contains some empty arrays too; these will convert to an empty string in the process, but will still have a comma before and after them.
In your example code above, the pagenamearray will end up with a value of [[[],"T01_Launch"],[[],"T02_Login"],[null,[],"T01_Launch"],[null,[],"T02_Login"]] - when converted to a String, this will result in ",T01_Launch,,T02_Login,,,T01_Launch,,,T02_Login". So instead of assigning it to the innerHTML value directly, you'll first have to filter out the empty arrays and null values.

Error in reading text from textarea in Javascript

In a webpage there is a textarea (id="text") and also a button (id="dlButton3").
What I have to do is to enter the text into the textarea. And when I press the button, then the following will be happened:
Text in the text area will be loaded into the function,
The text will be spitted with delimiters ""
There is a for loop to compare all the lengths of the strings, and
Print the longest one value
The problem is, with the following code, I can take the string from the text area but dun know why I cannot split the string, and it returns the error "Uncaught ReferenceError: targetString is not defined"
The code is as followed
function findlongestword(){
var testing = document.getElementById('text').value;
console.log(testing);
var strText = testing.split(" ");
var length = 0;
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function(){
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}
What can be the error?
Many thanks for your help in advance!
Read more about block scope targetString only exists within the loop
function findlongestword() {
var testing = document.getElementById('text').value;
var strText = testing.split(" ");
var length = 0;
var targetString = '';
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function() {
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}
"Uncaught ReferenceError: targetString is not defined"
You did not declare targetString before using it within your loop. Therefore javascript did not know where to find or 'Refer' to it after the loop ended.
By adding var targetString = ""; before the loop begins the problem will be solved.
function findlongestword(){
var testing = document.getElementById('text').value;
console.log(testing);
var strText = testing.split(" ");
//ADD HERE
var targetString = "";
var length = 0;
for (var i=0; i < strText.length; i++) {
if (length < strText[i].length) {
length = strText[i].length;
targetString = strText[i]
}
}
console.log (targetString);
}
window.onload = function(){
findlongestword();
document.getElementById("dlButton3").onclick = findlongestword;
}

Javascript missing ) after arguments list

A JavaScript function that takes a string argument and counts its properties.
I'm not sure why it's not working I think there is some problem with the console.log line.
function superCounter (TheWord) {
var NOWords = TheWord.split('').length;
var NOLetters = TheWord.length;
var NOSpaces = 0;
for (var i = 0; i < superCounter.length; i++)
if (TheWord[i] === " ") {
NOSpaces = +1;
}
var CTCharacters = TheWord.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
var TNCharacters = CTCharacters.length;
var AWLength = NOLetters / NOWords;
console.log("words:"
NOWords, "letters:"
NOLetters, "spaces:"
NOSpaces, "chars:"
TNCharacters, "avgLength:"
AWLength)
}
superCounter("The grintch made it happen");
Your console.log statement is wrong this is the write one.
You have missed commas after every argument. console.log arguments should be separated by ,.
// console.log("words:" NOWords, "letters:" NOLetters, "spaces:" NOSpaces, "chars:" TNCharacters, "avgLength:" AWLength)
console.log("words:", NOWords, "letters:", NOSpaces, "chars:", TNCharacters, "avgLength:", AWLength);

Get Unique values during Loop

I am looping through an array and getting the data that I need.
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
}
What I am trying to do at this point is only show unique data in the loop.
For example var transAccount could be in the array 5 times. I only one to display that in my table once. How can I go about accomplishing this ?
Final Array is constructed like so; just as an object:
finalArray.push({
transID: tmpTrans,
transAccount: tmpAccount,
amEmail: amEmail,
merchName: merchName,
amPhone: amPhone,
amName: amName
});
var allTransAccount = {};
for (var i = 0; i < finalArray.length; i++) {
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
var transAccount = finalArray[i].transAccount;
if(allTransAccount[finalArray[i].transAccount]) {
var transAccount = '';
}
else {
allTransAccount[transAccount] = true;
}
}
var merhcData = {};
var amName = {};
// and so on
for (var i = 0; i < finalArray.length; i++) {
merchData[finalArray[i].merchName] = finalArray[i].merchName;
amName[finalArray[i].amName] = finalArray[i].amName;
// and so on
}
If you are sure, that data in merchName will never be equal amName or other field - you can use one data object instead of several (merchData, amName...)
What you want is likely a Set. (see zakas for ES6 implementation. To emulate this using javascript, you could use an object with the key as one of your properties (account would be a good bet, as aperl said) which you test before using your raw array.
var theSet={};
for (var i = 0; i < finalArray.length; i++) {
var transAccount = finalArray[i].transAccount;
var merchName = finalArray[i].merchName;
var amName = finalArray[i].amName;
var amEmail = finalArray[i].amEmail;
var txnID = finalArray[i].transID;
if(!theSet[transAccount]){
//add to your table
theSet[transAccount]===true;
}
This will prevent entries of duplicate data.

How do I empty global arrays used in a pop up slideshow?

I've created a program where you can choose a set of images by checking checkboxes. The image URL's and the alt-texts are stored in two arrays. When clicking av button on the HTML-page you open a new window that calls on the arrays with window.opener.
When closing the new window I would like to empty the arrays. Otherwise the pictures chosen in the first round are displayed in the slideshow when opening it the second time. I understand you can empty arrays by this method: array.length= 0;
But where do I add the code? I'm quite lost. I'm pasting the code, perhaps someone can give me a hand.
var imgUrlList = [], imgTextList = [], //These arrays need to be emptied
windVar = null;
function init() {
var tags, i, openWindow;
tags = document.getElementsByClassName("unmarkedImg");
openWindow = document.getElementById("slideShowBtn");
openWindow.onclick = savePicsForSlideshow;
for (i = 0; i < tags.length; i++) {
tags[i].parentNode.onmouseover = showLargePict;
tags[i].parentNode.onmouseout = hideLargePict;
}
}
window.onload = init;
function showLargePict() {
var largePictTagDiv = this.getElementsByClassName("innerBox")[0];
var largePictTagParentDiv = largePictTagDiv.parentNode;
var imgTag = largePictTagParentDiv.getElementsByTagName('img')[0];
var checkBoxlargePict = largePictTagDiv.getElementsByTagName('input')[0];
if (checkBoxlargePict.checked)
imgTag.className = "markedImg";
else imgTag.className = "unmarkedImg";
largePictTagDiv.style.visibility = "visible";
} // End showLargePict
function hideLargePict() {
var largePictTag;
largePictTag = this.getElementsByClassName("innerBox")[0];
largePictTag.style.visibility = "hidden";
}
function savePicsForSlideshow() {
var innerBoxes = document.getElementsByClassName("innerBox");
for (i = 0; i < innerBoxes.length; i++) {
checkBoxlargePict = innerBoxes[i].getElementsByTagName('input')[0];
if (checkBoxlargePict.checked) {
var imgTagSrc = innerBoxes[i].getElementsByTagName('img')[0].src;
imgUrlList.push(imgTagSrc);
var spanTagText = innerBoxes[i].getElementsByTagName('span')[0].innerHTML;
imgTextList.push(spanTagText);
}
}
if (imgTextList.length > 0) {
newWindow(500, 600, "slideshow.htm");
}
}
function newWindow(width, height, filename) {
var windowProperties;
windowProperties = "top=100,left=100,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + width + ",height=" + height;
if (windVar != null) if (windVar.closed == false) windVar.close();
windVar = window.open(filename, "", windowProperties);
}
Please excuse my programming and English grammar shortcomings. I'm new to javascript.
//Henrik, Göteborg, Sweden.
At the beginning of the savePicsForSlideshow function, empty out each array.
imgUrlList.length = 0;
imgTextList.length = 0;
You can check if thw window is close with the property closed of the object window
if(window.closed)
{
array.length = 0;
}

Categories

Resources