I am retrieving values from server side using ajax call and here is the formate of the arraylist retrieved from server side..
[INCOMING,0,INETCALL,0,ISD,31.8,LOCAL,197.92,STD,73.2]
Now as per my need i have to break this arraylist in two variables like this..
var toc=INCOMING,INETCALL,ISD,LOCAL,STD
var callcost=0,0,31.8,197.92,73.2
I am trying to do it using for loop but i am not getting exact logic...
Here is my code..
$(function () {
$.ajax({
type: 'GET',
url: 'getdata',
async: false,
dataType: "text",
success: function (data) {
var values = [];
values = data;
values = values.replace('[', '');
values = values.replace(']', '');
var array = values.split(",");
for (var i in array) {
}
}
});
});
Please guys help me .
Thanks in advance.
Try to use $.isNumeric() like,
var arr=['INCOMING',0,'INETCALL',0,'ISD',31.8,'LOCAL',197.92,'STD',73.2];
var str=[],
num=[];
for(var i=0,len=arr.length;i<len;i++){
$.isNumeric(arr[i]) ? num.push(arr[i]) : str.push(arr[i]);
}
console.log(num);// returns array of numbers use num.join(',') to get string
console.log(str);// returns array of string use str.join(',') to get string
Demo
First off, the data seems to be an array already, just parse it with
var array = JSON.parse(data);
Or, if you have control over the server-side code too, make it return json-data instead of plain text. That way its a array ready to use when its passed into the callback!
If you want to get all numeric in the loop, use isNumeric, if its every other, do a %1 on the index, ie:
var a1 = [];
var a2 = [];
for(var i=0;i<array.length;i++){
if(i % 1 == 0){
a1.push(array[i]);
} else {
a2.push(array[i]);
}
}
check this fiddle http://jsfiddle.net/2sGjZ/
var myArray = ['INCOMING','0','INETCALL','0','ISD','31.8','LOCAL','197.92','STD','73.2'];
var tocArr = new Array();
var callcostArr = new Array();
var j = 0; var k= 0;
for ( var i = 0; i < myArray.length; i = i + 1 ) {
if(i % 2 == 1){
tocArr[j] = myArray[ i ];
j++;
}else{
callcostArr[k] = myArray[ i ];
k++;
}
}
var toc = tocArr.toString();
var callcost = callcostArr.toString();
alert( toc );
alert( callcost );
Related
I've searched high and wide for an answer but can't seem to find it. I am trying to alter my custom function that looks up sitemap URL's and the date they were updated to accept a range of inputs.
Here is the current function that works:
function sitemap(sitemapUrl, namespace) {
var array = [];
var xml = UrlFetchApp.fetch(sitemapUrl).getContentText();
var document = XmlService.parse(xml);
var root = document.getRootElement();
var sitemapNameSpace = XmlService.getNamespace("http://www.sitemaps.org/schemas/sitemap/0.9");
var urls = root.getChildren('url', sitemapNameSpace);
for (var i = 0; i < urls.length; i++) {
var loc = urls[i].getChild('loc', sitemapNameSpace).getText();
var lastmod = urls[i].getChild('lastmod', sitemapNameSpace).getText();
array.push([loc, lastmod]);
}
return array;
}
I've tried using Google's example below but doesn't seem to work however I incorporate it into my function. Any ideas?
function DOUBLE(input) {
if (input.map) { // Test whether input is an array.
return input.map(DOUBLE); // Recurse over array if so.
} else {
return input * 2;
}
}
Edit: This is how I tried to use Google's example for my function:
function sitemaps(sitemapUrl) {
var array = [];
var xml = UrlFetchApp.fetch(sitemapUrl).getContentText();
var document = XmlService.parse(xml);
var root = document.getRootElement()
var sitemapNameSpace = XmlService.getNamespace("http://www.sitemaps.org/schemas/sitemap/0.9")
var urls = root.getChildren('url', sitemapNameSpace)
for (var i = 0; i < urls.length; i++) {
var loc = urls[i].getChild('loc',sitemapNameSpace).getText();
var lastmod = urls[i].getChild('lastmod',sitemapNameSpace).getText();
array.push([loc, lastmod]);
}
if (sitemapUrl.map) {
return sitemapUrl.map(sitemaps);
} else {
return array
}
You are no using the same format as the Google example. As of right now you are checking if the input is an array after actually retrieving the data.
But you using fetch with an array as input could trigger an Error and the function may no get to the point where it checks if the sitemapUrl can be used with map.
Also take into account that map will call the function in every single element of the array and return an array with a result for each of element. So in your case B3:B6 would call the function for the value at B3, B4, B5 and B6 and return an array of length 4 with the result. For your case in which you want a single list you need to flattern the array afterwards
I would change your function to be like this:
function sitemaps(sitemapUrl) {
if (sitemapUrl.map) {
return sitemapUrl.map(sitemaps).flat();
} else {
var array = [];
var xml = UrlFetchApp.fetch(sitemapUrl).getContentText();
var document = XmlService.parse(xml);
var root = document.getRootElement()
var sitemapNameSpace = XmlService.getNamespace("http://www.sitemaps.org/schemas/sitemap/0.9")
var urls = root.getChildren('url', sitemapNameSpace)
for (var i = 0; i < urls.length; i++) {
var loc = urls[i].getChild('loc', sitemapNameSpace).getText();
var lastmod = urls[i].getChild('lastmod', sitemapNameSpace).getText();
array.push([loc, lastmod]);
}
return array
}
}
Although what you are doing is fine take into account that it also exists a way to retrieve all the request at the same time (
UrlFetchApp.fetch()) but for this specific case you would need to flatten a reshape the input array.
I have an algorithm where the user will enter a string and I will parse it into an array of 2+ dimensions. So, for example, the user can enter 1,2,3;4,5,6 and set the text to be parsed by the semicolon and the comma. The first pass through will create an array with 2 entries. The second pass through will create a 3 entry array in both prior spots.
The user can add or remove the number of text items to be used to parse the original string such as the semicolon or comma, meaning the resulting array can have as many dimensions as parsing items.
This doesn't seem like a difficult problem, but I have run into some snags.
Here is my code so far.
vm.parsers = [';', ','];
vm.inputString = "1,2,3,4,5;6,7,8,9,10";
function parseDatasetText( )
{
vm.real = vm.parseMe( vm.inputString, 0);
};
function parseMe( itemToParse, indexToParse )
{
if ( indexToParse < vm.parsers.length )
{
console.log('Parsing *'+itemToParse+'* with '+vm.parsers[indexToParse]);
var tempResults = itemToParse.split( vm.parsers[indexToParse] );
for (var a=0; a<tempResults.length; a++)
{
console.log('Pushing '+tempResults[a]);
tempResults[a] = vm.parseMe( tempResults[a], parseInt( indexToParse ) + 1 )
console.log('This value is '+tempResults[a]);
}
}else
{
console.log('Returning '+itemToParse);
return itemToParse
}
};
As you can see from the console logs, the algorithm spits out an undefined after the last parse, and the final answer is undefined.
Maybe I just haven't slept enough, but I was thinking that the array would recursively populate via the splits?
Thanks
function parseDatasetText(){
//composing parser from right to left into a single function
//that applies them from left to right on the data
var fn = vm.parsers.reduceRight(
(nextFn, delimiter) => v => String(v).split(delimiter).map(nextFn),
v => v
);
return fn( vm.inputString );
}
Don't know what else to add.
You can use a simple recursive function like the following (here an example with 3 different delimiters):
function multiSplit(xs, delimiters) {
if (!delimiters.length) return xs;
return xs.split(delimiters[0]).map(x => multiSplit(x, delimiters.slice(1)));
}
data = '1:10,2:20,3:30;4:40,5:50,6:60';
res = multiSplit(data, [';', ',', ':']);
console.log(res)
The following function should suit your requirements, please let me know if not
var parsers = [';', ',', ':'],
inputString = "1:a,2:b,3:c,4:d,5:e;6:f,7:g,8:h,9:i,10:j",
Result = [];
function Split(incoming) {
var temp = null;
for (var i = 0; i < parsers.length; i++)
if (incoming.indexOf(parsers[i]) >= 0) {
temp = incoming.split(parsers[i]);
break;
}
if (temp == null) return incoming;
var outgoing = [];
for (var i = 0; i < temp.length; i++)
outgoing[outgoing.length] = Split(temp[i])
return outgoing;
}
Result = Split(inputString);
try it on https://jsfiddle.net/cgy7nre1/
Edit 1 -
Added another inputString and another set of parsers: https://jsfiddle.net/cgy7nre1/1/
Did you mean this?
var inputString = "1,2,3,4,5;6,7,8,9,10";
var array=inputString.split(';');
for (var i=0;i<array.length;i++){
array[i]=array[i].split(',');
}
console.log(array);
I have the following javascript object
[Object { url="http://domain.com/abc", qty="1" }, Object { url="http://myurl.com/cde", qty="2" }]
I want to be able to loop through the object and output the URL using console.log() based on the qty variable.
So in this instance domain.com/abc would display once & the myurl.com/cde would display twice as the qty is set to 2.
I have something like the following but needs some work..
cart.forEach(function(value) {
var qty = value.qty;
var url = value.url;
var i = 0;
while ( i < qty ) {
// logic needed here (i believe)
i++;
}
}
That's how one can implement String.repeat in JS:
var repeatedString = Array(repeatsCount + 1).join(stringToRepeat);
... so in your case it'll be just ...
console.log(Array(+value.qty + 1).join(value.url));
Unary plus is a shortcut for Number(value.qty): it looks like you got a string there.
But it looks you actually need to collect all the urls instead. That's one possible way to do that:
var arrayOfUrls = [];
cart.forEach(function(value) {
for (var i = value.qty; i--) {
arrayOfUrls.push(value.url);
}
});
Alternative (.reduce-based):
var arrayOfUrls = cart.reduce(function(arr, value) {
for (var i = value.qty; i--) {
arr.push(value.url);
}
return arr;
}, []);
I have a long URL that contains some data that I need to pull. I am able to get the end of the URL by doing this:
var data = window.location.hash;
When I do alert(data); I receive a long string like this:
#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600
note in the example the access token is not valid, just random numbers I input for example purpose
Now that I have that long string stored in a variable, how can I parse out just the access token value, so everything in between the first '=' and '&. So this is what I need out of the string:
0u2389ruq892hqjru3h289r3u892ru3892r32235423
I was reading up on php explode, and others java script specific stuff like strip but couldn't get them to function as needed. Thanks guys.
DEMO (look in your debug console)
You will want to split the string by the token '&' first to get your key/value pairs:
var kvpairs = document.location.hash.substring(1).split('&');
Then, you will want to split each kvpair into a key and a value:
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != 'access_token')
continue;
console.log(v); //Here's your access token.
}
Here is a version wrapped into a function that you can use easily:
function getParam(hash, key) {
var kvpairs = hash.substring(1).split('&');
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != key)
continue;
return v;
}
return null;
}
Usage:
getParam(document.location.hash, 'access_token');
data.split("&")[0].split("=")[1]
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
var requiredValue = str.split('&')[0].split('=')[1];
I'd use regex in case value=key pair changes position
var data = "#token_type=Bearer&access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&expires_in=3600";
RegExp("access_token=([A-Za-z0-9]*)&").exec(data)[1];
output
"0u2389ruq892hqjru3h289r3u892ru3892r32235423"
Looks like I'm a bit late on this. Here's my attempt at a version that parses URL parameters into a map and gets any param by name.
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
function urlToMap(url){
var startIndex = Math.max(url.lastIndexOf("#"), url.lastIndexOf("?"));
url = url.substr(startIndex+1);
var result = {};
url.split("&").forEach(function(pair){
var x = pair.split("=");
result[x[0]]=x[1];
});
return result;
}
function getParam(url, name){
return urlToMap(url)[name];
}
console.log(getParam(str, "access_token"));
To answer to your question directly (what's between this and that), you would need to use indexOf and substring functions.
Here's a little piece of code for you.
function whatsBetween (_strToSearch, _leftText, _rightText) {
var leftPos = _strToSearch.indexOf(_leftText) + _leftText.length;
var rightPos = _strToSearch.indexOf(_rightText, leftPos);
if (leftPos >= 0 && leftPos < rightPos)
return _strToSearch.substring(leftPos, rightPos);
return "";
}
Usage:
alert(whatsBetween, data,"=","#");
That said, I'd rather go with a function like crush's...
try this
var data = window.location.hash;
var d1 = Array();
d1 = data.split("&")
var myFilteredData = Array();
for( var i=0;i<d1.length;i++ )
{
var d2 = d1[i].split("=");
myFilteredData.push(d2[1]); //Taking String after '='
}
I hope it helps you.
i have this code to get three values.
success: function(json){
$msg1 = parseFloat(json[0].valor1);
$msg2 = parseFloat(json[1].valor2);
$msg3 = parseFloat(json[2].valor3);
}
but now suppose that i need 200 values.
I'm not doing 200 times ...
$msg1 = parseFloat(json[0].valor1);
$msg2 = parseFloat(json[1].valor2);
$msg3 = parseFloat(json[2].valor3);
//...
$msg200 = parseFloat(json[199].valor200);
so, i need a loop, correct?
i tried something like this
for (i=0; i<200; i++) {
$msg(i+1) = parseFloat(json[i].valor(i+1));
i++;
}
but didn't work
thanks
This is why The Creator gave the world arrays.
var msgs = [];
for (var i = 0; i < 200; ++i)
msgs.push(parseFloat(json[i]['valor' + i]));
Note that your JSON data should also keep those "valor" properties as arrays, though in JavaScript you can deal with a bizarre naming scheme like that as in the example above.
edit — oops, typos fixed :-)
$msg = [];
for (var i=0; i<200; i++) {
$msg.push(parseFloat(json[i]["valor"+i]));
}
As stated by Pointy or:
var msgs = [];
for (i=0; i<200; i++) {
$msg[i] = parseFloat(eval('json[' + i + '].valor(' + i + '+1)'));
i++;
}
However eval is slow, so Pointy's answer is better.
var array = json.someid;// or json['someid'];
// json is returned not an array
var msgs = [];
$.each(array, function(index, e) {
msgs.push(parseFloat[e['valor' + index], 10);
});
when using parseFloat use the radix parameter unless you want bad things to happen;
javascript needs to be told for example not to parse octal;