Working on script in google-apps-script, any suggestions? - javascript
Problem: I am creating an array, or multiple arrays, to write values, and continue doing so until a certain value is drawn. The long view for this code is to, using these values to match one letter to another. (i.e. The Bombe used in WWII.) Except this will be completely digital. The Bombe was a decrypter that find that one letter is able to get mapped to another. (Enigma example will be posted in comments.) I am trying to decrpyt any message using this.
Understanding: I don't remember a lot of code especially since I have never used google-apps-script before. I no basic ideas, but some of the syntax's are different I am getting lost. (i.e.: instead of System.out.print(); it would be Logger.log(data);. That's really all I have gotten from it so far. I have some code worked out which can be found here.
Background: This is quite a lot of text to read I understand, but hear me out before you just flag me and move on. The hyperlink posted in the above comment under the words "Enigma example" shows the mapping that I am trying to do in reverse. I however need to create loops and variables that I do not remember how to create. I have information on the Enigma and Bombe: Enigma & Bombe info. I have done some searches on Google and the like, however nothing that I understand or benefit my end goal. All I have gotten is another link, which I will post in the comments, that shows me a basic loop as they put it.
What I need help with: I am asking for help in the following: Looping, variables and arrays. Suggestions will be the most valuable to me, because I am here to learn, not get my stuff done done by asking.
Ideas: Some ideas I have are, Garbage collectors, multi-dimensional array and/or just a sequence of possibilities. (See the "Enigma & Bombe info" link above.
For easy Copy/Pasting:
function bombeCode1() {
var fastRotor = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var mediumRotor = fastRotor;
var slowRotor = fastRotor;
var rows = 26;
var columns = 26;
for (var i=0; i < rows ; i++) {
Logger.log('Outer Loop: value of i : ' + i);
// Logger.log("Partition for Outer Loop");
// Logger.log(" ");
var fastRotorValue = fastRotor[i];
for (var j=0; j < columns ; j++) {
Logger.log('-Inner Loop value of j : ' +j);
//var fastRotorValue = fastRotor[i];
var medRotorValue = mediumRotor[j];
// Logger.log("---- " + fastRotorValue + " " + medRotorValue);
for (var k=0; k < 26 ; k++) {
// Logger.log('---- XXXX Third Loop value of k : ' + k);
//var fastRotorValue = fastRotor[i];
//var medRotorValue = mediumRotor[j];
var slowRotorValue = slowRotor[k];
Logger.log("---- XXXX " + fastRotorValue + " " + medRotorValue + " " + slowRotorValue);
}; //var objectNumberValuePair = {"0":"A", "1":"B", "2":"C","3":"D","4":"E","5":"F","6":"G","7":"H","8":"I",
// "9":"J","10":"K","11":"L","12":"M","13":"N","14":"O","15":"P","16":"Q","17":"R",
// "18":"S","19":"T","20":"U","21":"V","22":"W","23":"X","24":"Y","25":"Z"}
// Logger.log(slowRotorValue = objectNumberValuePair);
// Logger.log(medRoterValue = objectNumberValuePair);
// Logger.log(fastRoterValue = objectNumberValuePair);
}
}
}
Here is the code I modified a little bit, just to show the Loop values in the Logger print out.
function bombeCode1() {
var fastRotor = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var mediumRotor = fastRotor;
var slowRotor = fastRotor;
var rows = 3;
var columns = 6;
for (var i=0; i < rows ; i++) {
Logger.log('Outer Loop: value of i : ' + i);
Logger.log("Partition for Outer Loop");
Logger.log(" ");
for (var j=0; j < columns ; j++) {
Logger.log('----Inner Loop value of j : ' + j);
var fastRoterValue = fastRotor[i];
var medRoterValue = mediumRotor[j];
Logger.log("---- " + fastRoterValue + " " + medRoterValue);
for (var k=0; k < 6 ; k++) {
Logger.log('---- XXXX Third Loop value of k : ' + k);
var fastRoterValue = fastRotor[i];
var medRoterValue = mediumRotor[j];
var slowRotorValue = slowRotor[k];
Logger.log("---- XXXX " + fastRoterValue + " " + medRoterValue + " " + slowRotorValue);
};
}
}
}
Run it and see what you think. I'm sure it's not what you need, but got to start somewhere.
Related
How to know when a for loop is done without knowing how many iterations there will be?
using a for-loop in javascript i´m getting a not known amount of id´s, they´re not in an array but coming one by one. is there a way to get an alert when there are no more id´s to retrieve meaning the for loop is done? i can´t wrap my head around this, any help would be greatly appreciated. thanks! edited with code for clarification. function iterateDevices(api) { var count = api.getcount("devices"); var apiPath = dequotePath(api); for (var i = 0; i < count; i++) { var deviceApi = new LiveAPI(apiPath + " devices " + i); if (deviceApi) { var deviceName = deviceApi.get("name"); var deviceid = deviceApi.id; //var deviceName = deviceApi.get("parameters"); var className = deviceApi.get("class_name"); var deviceApiPath = dequotePath(deviceApi); var chainsCount; var chainApi; var j; if ((className == "DrumGroupDevice") || (className == "AudioEffectGroupDevice") || (className == "InstrumentGroupDevice")){ //post(deviceName + " id " + deviceid + "\'\n"); //outlet(0,deviceid); // arr.push(deviceName); if (deviceApi.get("can_have_chains") == 1) { chainsCount = deviceApi.getcount("chains"); // only racks have chains for (j = 0; j < chainsCount; j++) { // post("id" + deviceid + " found device " + deviceName + " at path \'" + deviceApiPath + "\'\n"); //outlet(0,deviceid); chainApi = new LiveAPI(deviceApiPath + " chains " + j); iterateDevices(chainApi); myFunction(); } chainsCount = deviceApi.getcount("return_chains"); // only racks have chains for (j = 0; j < chainsCount; j++) { //post("2 found device " + deviceName + "id"+deviceid + " at path \'" + deviceApiPath + "\'\n"); // outlet(0,deviceid); chainApi = new LiveAPI(deviceApiPath + " return_chains " + j); iterateDevices(chainApi); } } } } } } iterateDevices.local = 1;
The purpose of a for loop is to deal with a known number of iterations. If you want to deal with an unknown number of iterations, you would use a while loop. Of course, this is programming, so lets look at the crazy things we can do: Iterate over a collection. We dont necessarily know how many things are in the collection, but we may want to iterate over all of them. The number of things in the collection might even change as we're iterating. We can change how we iterate through the loop. That whole i++ part? What if we replace it with i += 2? Or what if it's i -=1? Or i += j and j changes while we're iterating? We can change how we break out of the loop. You can put a break statement in there to break out of the loop anytime. You can also change the conditional of the loop. What if i < 100 is replaced by i<j? Or what if we replace it with i<100 || q == true?
You may use a while loop instead of a for and insert a condition to terminate the loop. Using pseudo-code, you could do something like: other_ids = True // boolean var while(other_ids) { // do what you have to do other_ids = FuncionToCheckWhetherThereAreNewIds } FuncionToCheckWhetherThereAreNewIds should be a function that gives you true if there are new ids and false if there are not.
Increment counts of sites visited including TLDs and subdomains outputted to JSON
So I was asked to create an algorithm that when given a basic input of an array of counts and sites, it will output the accumulated visits to each TLD and Subdomain represented in a JSON object that will yield data like: 1120 com 800 google.com 310 reddit.com 60 mail.yahoo.com 10 mobile.sports.yahoo.com 50 sports.yahoo.com 10 stackoverflow.com 3 org 3 wikipedia.org 2 en.wikipedia.org 2 es.wikipedia.org 1 mobile.sports 1 sports The input is something like: // visits = [ "800,google.com", // "60,mail.yahoo.com", // "10,mobile.sports.yahoo.com", // "40,sports.yahoo.com", // "310,reddit.com", // "10,stackoverflow.com", // "2,en.wikipedia.org", // "1,es.wikipedia.org", // "1,mobile.sports" ] My code looks like this so far and I know its wrong, but my brain is melted at the moment and I am not sure how to proceed. I am not necessarily looking for you to write the algorithm for me, but I do want to understand logically how I could break this down. function getDomainHits(arr){ var splitCount = []; var splitDomains = []; var domainCountDict = {"Domains" : [],"Count" : 0}; for (var i = 0; i < arr.length; i++){ splitCount = arr[i].split(","); splitDomains = splitCount[1].split("."); for (var j = 0; j < splitDomains.length; j++){ if (!domainCountDict.Domain.includes(splitDomains[j])){ domainCountDict.Domain.push(splitDomains[j]); } } } console.log(domainCountDict); } As you can see I stopped here because I couldn't think of the best way to split these into different key, value pairs - one being domains and the other being the counts. Also my algorithm doesn't exactly follow the requirements.
So I figured out the algorithm. Define a variable - initialize it as an Array, and a dictionary to store the processed array data. var splitCount = []; var domainCountDict = {}; Then you need to take the Array of strings (arr - the function parameter) and iterate through it. On each iteration you need to split the string element into another Array to further process it. for (var i = 0; i < arr.length; i++){ splitCount = arr[i].split(","); ... } So for the example input data of // visits = [ "800,google.com", // "60,mail.yahoo.com", // "10,mobile.sports.yahoo.com", // "40,sports.yahoo.com", // "310,reddit.com", // "10,stackoverflow.com", // "2,en.wikipedia.org", // "1,es.wikipedia.org", // "1,mobile.sports" ] Iteration 0 would be split into an Array of ["800","google.com"] and assigned to Var splitCount. You would then need to access splitCount and because of the input formatting you don't need to create a for loop. I created a variable to store the current count of the site - which will always be element 0 because of the format of the input data. I didn't bother with input sanitation here because I didn't have time to create a map function that will turn the number elements into - well... numbers. I relied on the assumption that the input data will always have a number in the 0th index - which is terrible. Don't do this. var curCnt = 0; if (splitCount[0]){ curCnt = splitCount[0]; } This next chunk of logic hurt my brain a little bit because I needed to find a way to store each domain component and its count in the dict and determine if the other domains contained components that already existed and if so increment those. Lets make some more Arrays! var domain = []; var currentDom = []; if (splitCount[1] != undefined && splitCount[1]){ domain = splitCount[1].split("."); for (var j = domain.length - 1; j >= 0; j--){ ... } } Above you will see that created an Array to hold the domain components called domain and another called currentDom to hold the components that are being worked and have already been worked, because we want to make sure that we count com and google.com. Lets look inside of the for loop. for (var j = domain.length - 1; j >= 0; j--){ currentDom.unshift(domain.pop()); /*console.log("current iter: " + k + "\n" + "currentDom: " + currentDom.join(".") + "\n" + "current count: " + curCnt + "\n");*/ if (currentDom.join(".") in domainCountDict){ /*console.log("currentDom2: " + currentDom.join(".")); console.log("increment existing");*/ domainCountDict[currentDom.join(".")] += parseInt(curCnt); } if (!(currentDom.join(".") in domainCountDict)){ /*console.log("currentDom3: " + currentDom.join(".")); console.log("increment new");*/ domainCountDict[currentDom.join(".")] = parseInt(curCnt); //console.log(domainCountDict); } } Above you will see that I am iterating backwards in this loop to work the TLD first and then the domains/subdomains. I chose to pop the last element off the end of the current array and unshift it to the beginning of the new Array, currentDom. This will effectively let me work on a portion of the entire FQDN to determine if it has been included in the dictionary. I have a few if statements to determine if the currentDom is included in the array. I had to use Array.join() to accurately check if the string of the current domain components have been included in the dictionary. If not then the string of currentDom would be added as a key and the curCnt would be the value assigned. If so, then the value would be incremented. Because of my lazy input sanitation in the curCnt assignment I had to parse these as Int because JS dynamic types. I am sure there is a better way, but my brain hurts now. Finally make sure that you return the created dictionary on the outside of all of these for loops. The full algorithm is below // Sample output (in any order/format): // getTotalsByDomain(counts) // 1320 com // 900 google.com // 410 yahoo.com // 60 mail.yahoo.com // 10 mobile.sports.yahoo.com // 50 sports.yahoo.com // 10 stackoverflow.com // 3 org // 3 wikipedia.org // 2 en.wikipedia.org // 1 es.wikipedia.org // 1 mobile.sports // 1 sports let counts = [ "900,google.com", "60,mail.yahoo.com", "10,mobile.sports.yahoo.com", "40,sports.yahoo.com", "300,yahoo.com", "10,stackoverflow.com", "2,en.wikipedia.org", "1,es.wikipedia.org", "1,mobile.sports" ]; console.log(getDomainHits(counts)); function getDomainHits(arr){ var splitCount = []; var domainCountDict = {}; for (var i = 0; i < arr.length; i++){ splitCount = arr[i].split(","); var curCnt = 0; if (splitCount[0]){ curCnt = splitCount[0]; } var domain = []; var currentDom = []; if (splitCount[1] != undefined && splitCount[1]){ domain = splitCount[1].split("."); for (var j = domain.length - 1; j >= 0; j--){ currentDom.unshift(domain.pop()); /*console.log("current iter: " + k + "\n" + "currentDom: " + currentDom.join(".") + "\n" + "current count: " + curCnt + "\n");*/ if (currentDom.join(".") in domainCountDict){ /*console.log("currentDom2: " + currentDom.join(".")); console.log("increment existing");*/ domainCountDict[currentDom.join(".")] += parseInt(curCnt); } if (!(currentDom.join(".") in domainCountDict)){ /*console.log("currentDom3: " + currentDom.join(".")); console.log("increment new");*/ domainCountDict[currentDom.join(".")] = parseInt(curCnt); //console.log(domainCountDict); } } } } return domainCountDict; }
Split javascript string into array
I have this javscript string: response "[[[#],[b,#],[b,w,b,b,b,#],[b,#],[b,w,w,b,#]],[[b,#],[b,b,#],[b,b,w,#],[b,b,b,#],[b,b,#]],[[b,#],[b,b,b,b,#],[b,w,#],[b,b,b,#],[b,#]],[[b,#],[b,#],[w,w,w,#],[b,b,w,w,#],[b,w,#]],[[b,#],[b,b,b,b,#],[b,w,b,#],[b,w,#],[b,b,#]]]" This corresponds to a board game and which field (e.g [b,w,b,b,b,#]) is a cell with black and white pieces. The # is the top of the stack. I need to parse this in order to create an array of tiles. I have this: XMLscene.prototype.readBoard = function(data){ var response = data.target.response; console.log("REPONSE NO PARS" + response); response = response.split("],"); console.log("REPONSE " + response); response[0] = response[0].substring(1); response[5] = response[5].substring(0, response[5].length - 2); for(var i = 0; i < response.length; i++) { response[i] = response[i].substring(1); response[i] = response[i].split("),"); for(var j = 0; j < response[i].length; j++) response[i][j] = response[i][j].substring(5); } this.scene.board.loadTiles(response); //this.scene.client.getPrologRequest('quit', 0, 1); }; to be parsed in this function: gameBoard.prototype.loadTiles = function(board){ console.log("BOARD : " + board); this.tiles = []; for (var i = 0; i < board.length; i++){ for (var j = 0; j < board[i].length; j++){ var player = board[i][j].split(",")[0]; console.log("PLAYER : " + player); var type = board[i][j].split(",")[1]; console.log("Type : " + type); if (type != "e") { var tile = this.createTile(type, this.scene ,i*6 + j+100, player); tile.line = i; tile.col = j; this.tiles.push(tile); } } } } The board structure I want is something like this: for the first stack: [#] It's an empty cell [b,#] - A cell with one piece - black [b,w,w,b,#] - A cell with a black piece in the bottom, then two white pieces and a black on the top, therefore the black player is the owner of the stack! The stack owner is the player that have his piece on the top of the stack (closest to #) Is there any way to get an array with each stack being the element of it? Regards
You could transform the data to JSON like this, ignoring the hashes as they seem to give information that is already known (the stack ends at the right): var response = JSON.parse(response.replace(/,?#/g, '').replace(/[bw]/g, '"$&"')); Then you can for instance identify the current player for a stack at (i, j), like this: var player = board[i][j].slice(-1)[0]; // last element on the stack Snippet: // Sample data var response = "[[[#],[b,#],[b,w,b,b,b,#],[b,#],[b,w,w,b,#]],[[b,#],[b,b,#],[b,b,w,#],[b,b,b,#],[b,b,#]],[[b,#],[b,b,b,b,#],[b,w,#],[b,b,b,#],[b,#]],[[b,#],[b,#],[w,w,w,#],[b,b,w,w,#],[b,w,#]],[[b,#],[b,b,b,b,#],[b,w,b,#],[b,w,#],[b,b,#]]]"; // Convert to nested array var board = JSON.parse(response.replace(/,?#/g, '').replace(/[bw]/g, '"$&"')); // Print the stack at 3, 3 console.log(board[3][3].join(',')); // Print player for that stack: console.log(board[3][3].slice(-1)[0]);
A quick and dirty solution is to quote all your elements by using String.prototype.replace() and then put the entire result in an eval(): var str = "[[[#],[b,#],[b,w,b,b,b,#],[b,#],[b,w,w,b,#]],[[b,#],[b,b,#],[b,b,w,#],[b,b,b,#],[b,b,#]],[[b,#],[b,b,b,b,#],[b,w,#],[b,b,b,#],[b,#]],[[b,#],[b,#],[w,w,w,#],[b,b,w,w,#],[b,w,#]],[[b,#],[b,b,b,b,#],[b,w,b,#],[b,w,#],[b,b,#]]]"; var res = eval(str.replace(/[bw#]/g, "'$&'")); console.log(res);
Modify your string to look like this... var myString = '[[[#],[b,#],[b,w,b,b,b,#],[b,#],[b,w,w,b,#]],[[b,#],[b,b,#],[b,b,w,#],[b,b,b,#],[b,b,#]],[[b,#],[b,b,b,b,#],[b,w,#],[b,b,b,#],[b,#]],[[b,#],[b,#],[w,w,w,#],[b,b,w,w,#],[b,w,#]],[[b,#],[b,b,b,b,#],[b,w,b,#],[b,w,#],[b,b,#]]]' replace elements with "" Now run following: var myArrayObject = JSON.parse(myString); You just converted it to array. Sample code: https://fiddle.jshell.net/3gvzmwef/21/
Pull information from a data file?
I have over 170000 entries of data in data file in this format: 1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;: 1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;: Now each data array starts with a unique id and i was wondering is there a convenient way to push each entry 1479661 then 1479662 every second to an array and assign the values within the unique id into 6 fields that update. Now I ask if there is a more convenient way as currently I am using this method: Data comprises of three chunks in a single line Split the link into chunks var chunkOne = [1479661]; var chunkTwo = [-1,1,-1,-898,-769,0.00,-1,2,-1,-96,-1402,0.00,-1,3,-1,117,-1397,0.00,-1,4,-1,-4,-2420,0.00,4,5,-1,5570,4395,0.00,4,6,-1,5570,4395,0.00,4,7,-1,5570,4395,0.00,4,8,-1,5570,4395,0.00,4,9,-1,5570,4395,0.00,4,10,-1,5570,4395,0.00,4,11,-1,5570,4395,0.00,4,12,-1,5570,4395,0.00,4,13,-1,5570,4395,0.00,4,14,-1,5570,4395,0.00,-1,15,-1,913,-3533,0.00,4,16,-1,5570,4395,0.00,4,17,-1,5570,4395,0.00,4,18,-1,5570,4395,0.00,4,19,-1,5570,4395,0.00,4,20,-1,5570,4395,0.00,4,21,-1,5570,4395,0.00,4,22,-1,5570,4395,0.00,4,23,-1,5570,4395,0.00,4,24,-1,5570,4395,0.00,4,25,-1,5570,4395,0.00,4,26,-1,5570,4395,0.00,4,27,-1,5570,4395,0.00,4,28,-1,5570,4395,0.00,4,29,-1,5570,4395,0.00]; var chunkThree = [117,-1397,7,7.00,"A","Dead"]; Then get length of each array: var chunkOneLength = chunkOne.length; var chunkTwoLength = chunkTwo.length; var chunkThreeLength = chunkThree.length; Pick out the nth value in the array depending on the data chunk: //uniqueID set as first for (var i = 0; i < chunkOneLength; i = i + 1) { // useful code would go here alert("This is the unique ID " + chunkOne[i]); } //teamval for (var i = 0; i < chunkTwoLength; i = i + 6) { // useful code would go here alert("This is the teamVal " + chunkTwo[i]); } Now the only problem I see with this method, is that the original data array will need to be formatted and separated into chunks every time.
As you have a separator on each section i.e. : you can actually use split to split them up like below and push them into a array and only have to do 2 loops - firstly pushing the split data in a new array and then looping through them and populating the structure. Please note as long as each chunk of data is separated with : this will work with anything even if you expand the data later. obviously it will not work if you remove the : separator. example below: var splitChucks = []; var chucks = [ "1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:", "1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:"]; for (var i = 0; i < chucks.length; i++){ splitChucks.push(chucks[i].split(':')) } for (var h = 0; h < splitChucks.length; h++) { alert("This is the unique ID " + splitChucks[h][0]); alert("This is the teamVal " + splitChucks[h][1]); } Hope this helps, this is a much more efficient way to do your task :)
var splitChucks = []; var chucks = [ "1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:", "1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:"]; for (var i = 0; i < chucks.length; i++){ splitChucks.push(chucks[i].split(':')) } for (var h = 0; h < splitChucks.length; h++) { alert("This is the unique ID " + splitChucks[h][0]); alert("This is the teamVal " + splitChucks[h][1]); }
One of the best purposes of an unique ID is to act as an index. So, instead of iterating over your index array (chunkOne), use ID as an Object key! // 1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;: var data = { 1479661: [ -1,1,-1,-898,-769,0.00,-1,2,-1,-96,-1402,0.00,-1,3,-1,117,-1397,0.00,-1,4,-1,-4,-2420,0.00,4,5,-1,5570,4395,0.00,4,6,-1,5570,4395,0.00,4,7,-1,5570,4395,0.00,4,8,-1,5570,4395,0.00,4,9,-1,5570,4395,0.00,4,10,-1,5570,4395,0.00,4,11,-1,5570,4395,0.00,4,12,-1,5570,4395,0.00,4,13,-1,5570,4395,0.00,4,14,-1,5570,4395,0.00,-1,15,-1,913,-3533,0.00,4,16,-1,5570,4395,0.00,4,17,-1,5570,4395,0.00,4,18,-1,5570,4395,0.00,4,19,-1,5570,4395,0.00,4,20,-1,5570,4395,0.00,4,21,-1,5570,4395,0.00,4,22,-1,5570,4395,0.00,4,23,-1,5570,4395,0.00,4,24,-1,5570,4395,0.00,4,25,-1,5570,4395,0.00,4,26,-1,5570,4395,0.00,4,27,-1,5570,4395,0.00,4,28,-1,5570,4395,0.00,4,29,-1,5570,4395,0.00,117,-1397,7,7.00,"A","Dead" ] // More data... }; Object.keys(data).forEach(function(key) { console.log('This is ID ' + key); data[key].forEach(function(value,index,array) { console.log('Index ' + index + ' of data key ' + key + ':'); console.log(data[key][index]); }); }); Test this on any modern browser's console or node.js instance to see results.
javascript replace string/html from array
I try to create a system replacement for ToolTip. I already create a version but its not quite optimal (search a better way to do it) here's a fiddle : http://jsfiddle.net/forX/Lwgrug24/ I create a dictionary (array[key]->value). the array is order by length of the key. each key is a word or an expression, the value is the definition of the expression. So, I replace the expression by a span (could/should be a div). The span is used for the tooltip (I use the data-title as tooltip text). because some word is reused in expression, I need to remove expression already with tooltip (in real life think of father/grandfather, you dont want the definition of father inside grandfather). For replacement I use a ramdom value. That's the worst of this code. You could make comment or post a new way to do it. maybe someone already did it. Clarification : I think my way to do it is wrong by using a string for replacement. Or it could be more secure. How should I do it? html : <div class="container"> one two three four five six seven eight nine ten </div> javascript : $(function() { var list = [ {'k':'one two three four five','v':'First five number.'}, {'k':'four five six seven','v':'middle number.'}, {'k':'six seven eight','v':'second middle number.'}, {'k':'two','v':'number two.'}, {'k':'six','v':'number six.'}, {'k':'ten','v':'number ten.'} ]; $(".container").each(function(){ var replacement = new Array(); for (i = 0; i < list.length; i++) { var val = list[i]; var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); replacement[rString + "_k"] = htmlEncode(val["k"]); replacement[rString + "_v"] = htmlEncode(val["v"]); var re = new RegExp("(" + val["k"] + ")","g"); $(":contains('" + val["k"] + "')",$(this).parent()).html(function(_, html) { var newItem = '<span class="itemWithDescription" ' + 'data-title="' + rString + "_v" + '">' + rString + "_k" + '</span>'; return html.replace(re, newItem); }); } for (var k in replacement){ $(this).html($(this).html().replace(k,replacement[k])); console.log("Key is " + k + ", value is : " + replacement[k]); } }); $(document).tooltip({ items:'.itemWithDescription', tooltipClass:'Tip', content: function(){ var title = $(this).attr("data-title"); if (title == ""){ title = $(this).attr("title"); //custom tooltips } return title; } }); }); function randomString(length, chars) { var result = ''; for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))]; return result; } function htmlEncode(value){ //create a in-memory div, set it's inner text(which jQuery automatically encodes) //then grab the encoded contents back out. The div never exists on the page. return $('<div/>').text(value).html(); } I added a little thing. on the random function, I put a | and } for every char, its bigger but there's not much chance to have a conflic with an expression. for (var i = length; i > 0; --i) result += '|' + ( chars[Math.round(Math.random() * (chars.length - 1))] ) + '}' ; http://jsfiddle.net/forX/Lwgrug24/3/