Need to concatenate strings from two arrays [duplicate] - javascript

This question already has answers here:
is the + operator less performant than StringBuffer.append()
(13 answers)
Closed 9 years ago.
I have two jQuery variables. Each variable is a text string containing words separated by a comma.
var myFirstVariable = green,blue
var mySecondVariable = circle,triangle
I would like to have a third variable retured like this:
var myThirdVariable = greencircle,bluecircle,greentriangle,bluetriangle
The order of the words in myThirdVariable is not important. But my first two variables can contain any number of words, so if
var myFirstVariable = green,blue,yellow
var mySecondVariable = circle,triangle,square
Then I need my third variable to returned like this:
var myThirdVariable = greencircle,bluecircle,yellowcircle,greentriangle,bluetriangle,yellowtriangle,greensquare,bluesquare,yellowsquare
I think I need to push() both variables into an array but I'm struggling with this area of jQuery. Hope someone can shed some light on this. Many thanks.

I'm struggling with this area of jQuery
That's simply because the jQuery library has no tools for this kind of work.
Use the native JavaScript functionality instead, specifically the String split method, the Array join method, the string concatenation operator + and for-loops:
var myFirstVariable = "green,blue"
var mySecondVariable = "circle,triangle";
var firstArr = myFirstVariable.split(","),
secondArr = mySecondVariable.split(","),
thirdArr = [];
for (var i=0; i<firstArr.length; i++)
for (var j=0; j<secondArr.length; j++)
thirdArr.push(firstArr[i]+secondArr[j]);
var myThirdVariable = thirdArr.join(",");

You can use the plain old string split method to get 2 arrays.
http://www.w3schools.com/jsref/jsref_split.asp
You could then use nested for loops to push the new strings into your 3rd array and then use the join method to create the final string.
http://www.w3schools.com/jsref/jsref_join.asp

Try
var myFirstVariable = 'green,blue'
var mySecondVariable = 'circle,triangle'
var myThirdVariable = fn(myFirstVariable, mySecondVariable);
console.log(myThirdVariable)
function fn(fv, sv){
var fa = fv.split(','), sa = sv.split(','), ta = [];
for(var i = 0; i < fa.length; i++){
for(var j = 0; j < sa.length; j++){
ta.push(fa[i] + sa[j])
}
}
return ta.join(',')
}
Demo: Fiddle

OK so you don't need jquery to achieve this, just JavaScript.
check out this answer here to help you:
How to merge two arrays in Javascript and de-duplicate items

Related

How do I show only numbers from a Javascript array that has both numbers and letters use parseInt?

I'm trying to use the parseInt to show only numbers from the following array:
1,2,a,b
Here is my javascript code so far:
var filter_list = ["1,2,a,b"];
function myFunction() {
parseInt(filter_list);
return filter_list;
}
document.getElementById("display").innerHTML = filter_list;
Maybe my idea isn't even going to work. Would love some feedback.
You have array with one element that is string, so you could use join and split and then filter method.
var data = ["1,2,a,b"];
var numbers = data.join(",").split(",").filter(Number);
console.log(numbers)
First, you have to know that each element of the array has to have teir own " ". Like that:
var filter_list = ["1","2","a","b"];
then, if you want to know the elements that are numbres, you can do something like that:
var filter_list = ["1","2","a","b"];
for(i = 0; i < filter_list.length; i++ {
if (!isNaN(ParseInt(filter_list[i])){
var new_array = [];
new_array[i] = filter_list[i];
}
}
document.getElementById("display").innerHTML = new_array;
I don't know if is that what you wanted to know.

How to loop sql data into array and adding keys? [duplicate]

This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 5 years ago.
i would like to know how to loop all of my sql datas (that i parsed into a json table) into an array, with adding a key to each of them.
I know how i can loop all of the data into an simple string like this :
var dbString ="";
for(i = 0; i < result.response.length; i++)
{
dbString += result.response[i].names;
}
This would just look like this
var dbString = "James Michael Alfred....";
But how can i make this look like this :
var dbString = {"James":1, "Michael":2, "Alfred":3, .....}
Thanks.
It's a really unique demand to organise a list of names like you want, but here it is:
var dbString = {};
var names = result.response;
for(var i = 0; i < names.length; i++){
dbString[names[i]] = i + 1;
}

Google scripts. TypeError: Cannot call method "replace" of undefined

First post please go easy on me.
I have an array that looks something like this [BTC-LTC, BTC-DOGE, BTC-VTC] I am trying to change all the "-" with "_". But am having trouble with using the .replace() method. Here is my code.
var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
var str = JSON.stringify(array[i]);
var res = str.replace("-","_");
fixedArray.push(res);
};
I tried without using the JSON.stringify but that didn't work either. I have also tried to first create var str = String(); this also did not work. Is it possible that the method .replace() is not available in google scripts?
In your example var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
should be
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
However I gather from the comments that this is just a typo in your initial example.
var str = JSON.stringify(array[i]); is redundant. You can just do var str = array[i]; Since the value in the array is already a string, there's no need to turn it into one again - the "stringify" method expects to be given an object or array to work on.
However the main problem is that your for loop goes on one too many iterations. Arrays are zero-based, so you need to stop looping when the index is 1 less than the length of the array, not equal to it. e.g. if array.length is 10 then there are 10 indices, but they start at 0, so the indices are 0,1,2,3,4,5,6,7,8,9. If your loop goes on to equal to array.length, then on the last loop array[10] will be out of bounds, and it's only this last iteration which is giving you the undefined error.
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
var fixedArray = [];
for (var i = 0; i < array.length; i++) {
var str = array[i];
var res = str.replace("-","_");
fixedArray.push(res);
}
If I understood correctly, you're trying to edit strings, not variables, so you need quotes in your array, and a g in your replace in case you have multiple things to replace :
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
fixedArray.push(array[i].replace(/-/g, '_'));
};
code is working fine if we change as below:
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];

How to extract values from a string in javascript?

I need some help with extracting values from a cookie using javascript.
The string in a cookie looks something like this:
string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
By using string.split() and string.replace() and a some ugly looking code I've somehow managed to get the values i need (price, name, shipping, quantity). But the problem is that sometimes not all of the strings in the cookie are the same. Sometimes the sting in a cookie will look something like this :
string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
with some items having color and size as parameters and sometimes only one of those.
Is there some more efficient way to explain to my computer that i want the part of the string after 'price=' to be a variable named 'price' etc.
I hope I'm making sense I've tried to be as precise as I could.
Anyway, thank you for any help
EDIT: I just wanted to say thanks to all the great people of StackOverflow for such wonderfull ideas. Because of all of your great suggestions I'm going out to get drunk tonight. Thank you all :)
Let's write a parser!
function parse(input)
{
function parseSingle(input)
{
var parts = input.split('||'),
part,
record = {};
for (var i=0; i<parts.length; i++)
{
part = parts[i].split('=');
record[part[0]] = part[1];
}
return record;
}
var parts = input.split('++'),
records = [];
for (var i=0; i<parts.length; i++)
{
records.push(parseSingle(parts[i]));
}
return records;
}
Usage:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var parsed = parse(string);
/* parsed is:
[{id: "1", price: "500", name: "Item name", shipping: "0", quantity: "2"},
{id: "2", price: "1500", name: "Some other name", shipping: "10", quantity: "2"}]
*/
You can achieve this using regular expressions. For example, the regex /price=([0-9]+)/ will match price=XXX where XXX is one or more numbers. As this part of the regex is surrounded by parenthesis it explicitly captures the numeric part for you.
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
var priceRegex = /price=([0-9]+)/
var match = string.match(priceRegex);
console.log(match[1]); // writes 500 to the console log
Try that:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var obj = new Array();
var arr = string.split('||');
for(var x=0; x<arr.length;x++){
var temp = arr[x].split('=');
obj[temp[0]] = temp[1]
}
alert(obj['id']); // alert 1
First, split your string into two (or more) parts by ++ separator:
var strings = myString.split('++');
then for each of the strings you want an object, right? So you need to have an array and fill it like that:
var objects = [];
for (var i = 0; i < strings.length; ++i) {
var properties = strings[i].split('||');
var obj = {};
for (var j = 0; j < properties.length; ++j) {
var prop = properties[j].split('=');
obj[prop[0]] = prop[1]; //here you add property to your object, no matter what its name is
}
objects.push(obj);
}
thus you have an array of all objects constructed from your string. Naturally, in real life I'd add some checks that strings indeed satisfy the format etc. But the idea is clear, I hope.
If you can replace the || with &, you could try to parse it as if it were a query string.
A personal note - JSON-formatted data would've been easier to work with.
I would attach the data to a javascript object.
var settingsObj = {};
var components = thatString.split('||');
for(var j = 0; j < components.length; j++)
{
var keyValue = components[j].split('=');
settingsObj[keyValue[0]] = keyValue[1];
}
// Now the key value pairs have been set, you can simply request them
var id = settingsObj.id; // 1 or c1
var name = settingsObj.name; // Item Name, etc
You're already using .split() to break down the string by || just take that a step further and split each of those sections by = and assign everything on the left the field and the right the value
This should get the first match in the string:
string.match(/price=(\d{1,})/)[1]
Note this will only match the first price= in the string, not the second one.
If you can use jQuery, it wraps working with cookies and lets you access them like:
Reading a cookie:
var comments = $.cookie('comments');
Writing a cookie:
$.cookie('comments', 'expanded');
This post by someone else has a decent example:
http://www.vagrantradio.com/2009/10/getting-and-setting-cookies-with-jquery.html
If you can't use jQuery, you need to do standard string parsing like you currently are (perhaps regular expressions instead of the string splitting / replacing might trim down your code) or find some other javascript library that you can use.
If you like eye candies in your code you can use a regexp based "search and don't replace" trick by John Resig (cached here) :
var extract = function(string) {
var o = {};
string.replace(/(.*?)=(.*?)(?:\|\||$)/g, function(all, key, value) {
o[key] = value;
});
return o;
};
Then
var objects = string.split('++'),
i = objects.length;
for (;i--;) {
objects[i] = extract(objects[i]);
}
You could do something like this, where you eval the strings when you split them.
<html>
<head>
<script type="text/javascript">
var string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var mySplitResult = string.split("||");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
var assignment = mySplitResult[i].split("=");
eval(assignment[0] + "=" + "\""+assignment[1]+"\"");
}
document.write("Price : " + price);
</script>
</head>
<body>
</body>
</html>
var str = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var items = str.split("++");
for (var i=0; i<items.length; i++) {
var data = items[i].split("||");
for (var j=0; j<data.length; j++) {
var stuff = data[j].split("=");
var n = stuff[0];
var v = stuff[1];
eval("var "+n+"='"+v+"'");
}
alert(id);
}
EDIT: As per JamieC's suggestion, you can eliminate eval("var "+n+"='"+v+"'"); and replace it with the (somewhat) safer window[n] = v; -- but you still have the simple problem that this will overwrite existing variables, not to mention you can't tell if the variable color was set on this iteration or if this one skipped it and the last one set it. Creating an empty object before the loop and populating it inside the loop (like every other answer suggests) is a better approach in almost every way.
JSON.parse('[{' + string.replace(/\+\+/g, '},{').replace(/(\w*)=([\w\s]*)/g, '"$1":"$2"').replace(/\|\|/g, ',') + '}]')
Convert the string for JSON format, then parse it.

Array read problem for map of vectors of strings in javascript

I am a newbie in JS. Here is my code and I believe it should work... but it doesn't.
var pop = new Array();
pop['la'] = new Array('nt','gb','te');
pop['sa'] = new Array('nt','gb');
pop['ha'] = new Array('pc','pa');
var _ecpop="la";
for (var i = 0; i < pop[_ecpop].length; i++)
{
document.write(pop[_ecpop][i]);
}
I just do not know any alternate way to have a map of vectors of a string.
Thanks,
Amir.
That's not an Array, but a Javascript Object, containing Arrays in it's properties. You can use Object and Array literals for that. The advantage is that your code looks much cleaner. There are seldom reasons to use new Array or new Object in javascript code (see for example this SO Question).
var pop = {
la: ['nt','gb','te'],
sa: ['nt','gb'],
ha: ['pc','pa']
}
now you can use
for (var i = 0; i < pop.la.length; i++) {
console.log(pop.la[i]);
}
if a property label is stored in a variable (like you _ecpop), you can use bracket notiation to retrieve it's value:
var laArr = pop[_ecpop];
for (var i = 0; i < laArr.length; i++) {
console.log(laArr[i]);
}
The other way around you can assign a label to an Object:
var _ecpop = 'la';
pop[_ecpop] = ['nt','gb','te'];
document.write is not the preferred way to put things on your page. It's better and just as easy to use some element with an id, and write output to it using innerHTML, for example
document.getElementById('myOutput').innerHTML = '[some output here]';
In javascript, an array can only have numeric indexes, if you want to use textual indexes, you should use object instead.
var pop = new Object();
or
var pop = {};
and then:
pop['la'] = new Array('nt','gb','te');
However, as an object is not an array, it has no length member, but just as an array you can use the for..in to go through all of its values.
Using document.write is not a good choice as it only works during the document loading, not after it. Try to use text nodes or innerhtml instead.

Categories