Javascript How to add array with another array into a new array? - javascript

So my challenge right now is unable to add array with another array into another new array.
my code:
var disabletimerange = { basedonservicetype: "", basedonservicer: "" }
var arr = [{"StartTime":"09:00:00","EndTime":"09:10:00"},{"StartTime":"10:00:00","EndTime":"15:00:00"}]
for (var xx = 0; xx < arr.length; xx++) {
var bookedStartTime, bookedEndTime
bookedStartTime = arr[xx].StartTime.slice(0, -3)
bookedEndTime = arr[xx].EndTime.slice(0, -3)
if (disabletimerange.basedonservicer === "") {
var disabletimealreadybookedtiming = "[" + '"' + bookedStartTime + '"' + "," + '"' + bookedEndTime + '"' + "]"
disabletimerange.basedonservicer = JSON.parse(disabletimealreadybookedtiming)
} else {
var disabletimealreadybookedtiming = "[" + '"' + bookedStartTime + '"' + "," + '"' + bookedEndTime + '"' + "]"
disabletimerange.basedonservicer = "[" + "[" + disabletimerange.basedonservicer + "]" + "," + disabletimealreadybookedtiming + "]"
disabletimerange.basedonservicer = JSON.parse(disabletimerange.basedonservicer)
}
Uncaught SyntaxError: Unexpected number in JSON at position 3 --> at the last line it cannot parse.
In short, what i want is basically 2 array stick tgt instead of adding into it
var y = ["hi", "123"]
var x = ["yo", "312"]
this
[["hi", "123"], ["yo", "312"]] instead of ["hi", "123", "yo", "312"]
and it must be array. not text form

You can do:
var y = ["hi", "123"]
var x = ["yo", "312"]
var result = [x, y]
console.log(result)

As you described
How to add array with another array into a new array?
create a new array
push your arrays into this new array one by one
let x = [1,2];
let y = [3.4];
let z = [];
z.push(x)
z.push(y);
console.log(z);

Related

Dynamically change element name in jquery

The following is my element id and I want to update it dynamically.
invoice[46][ap_details][4][ap_header_id]
I want to update only second number, i.e. [4], like this:
invoice[46][ap_details][5][ap_header_id]
I am using below code which is updating both the values.
var strNewName = $(this).attr('name').replace(/\[\d+\]/g, function(strName) {
strName = strName.replace(/[\[\]']+/g, '');
var intNumber = parseInt(strName) + 1;
return '[' + intNumber + ']';
});
Any help would be appreciated.
var strName = "invoice[46][ap_details][4][ap_header_id]";
var parts = strName.split('[');
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
var strNewName = parts.join('[');
console.log(strNewName);
If you don't want to use arrow functions replace this line:
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
with this:
parts[3] = parts[3].replace(/^\d+/, function(n) { return +n + 1; });
Explanation:
split will return an array like this:
[
"invoice",
"46]", // parts[1] to change this
"ap_details]",
"4]", // parts[3] to change this (and so on, you do the math)
"ap_header_id]"
]
The /^\d+/ will match any number at the begining (no need for the g modifier).
Replace with +n + 1 not n + 1 because n is a string, you have to force the interpretter to use it as a number or otherwise this "4" + 1 will result to this "41".
Then after you change what you want, join the parts using join with the same character you used for splitting ([).
Using this regex /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi you can construct the string back and change your integer.
var match = /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi.exec(youString);
//group 6 is your digit.
var newId = parseInt(match[6].replace("\[\]", "")) + 1;
var newString = match[1] + match[3] + match[4] + "[" + newId + "]" + match[7];
Here is a fiddle with the answer https://jsfiddle.net/gzfud9vc/
Maybe dont use regex to build your element id. You can do its as follows as well:
var id = 5
var name = "invoice[46][ap_details][";
name += id;
name += "][ap_header_id]";
var toReplace = "invoice[46][ap_details][~~id~~][ap_header_id]"
var replaced = toReplace.replace(/~~id~~/g, id);
console.log(name);
console.log(replaced);

Returning a String instead of looping print statement

I'm new to Javascript and I'm curious as to how to store values in a string and then return it. In the example below 2 numbers are picked, for example 2 and 8, and the program should return 2x1 =2, 2x2=4,..... all the way up to 2x8 =16. This can obviously be done by constantly looping a print statement as I have done, but how would I be able to store all the values in a String and then return the string.
function showMultiples (num, numMultiples)
{
for (i = 1; i < numMultiples; i++)
{
var result = num*i;
console.log(num + " x " + i + " = " + result+ "\n");
}
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2,8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3,2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5,4));
function showMultiples(num, numMultiples) {
// the accumulator (should be initialized to empty string)
var str = "";
for (i = 1; i < numMultiples; i++) {
var result = num * i;
// use += to append to str instead of overriding it
str += num + " x " + i + " = " + result + "\n";
}
// return the result str
return str;
}
var mulOf5 = showMultiples(5, 10);
console.log("multiples of 5 are:\n" + mulOf5);
The operator += add the a value (right operand) to the previous value of the left operand and stores the result in the later. So these two lines are the same:
str = str + someValue;
str += someValue;
You could just use string concatenation:
var finalResult = ""
...in your loop...
finalResult += num + " x " + i + " = " + result+ "\n"
Often you can also just collect the results in an array and use join to append them.
var lines = [];
... in your loop:
lines.push(num + " x " + i + " = " + result);
... afterwards
console.log(lines.join("\n"));
In case you wanted to use ES6 syntax using backticks for a template string, you can use the below. This is a little more readable and is exactly where it is useful (so long as you can use ES6 wherever you're using JavaScript).
function showMultiples(num, numMultiples){
let result = '';
for(let i = 1; i < numMultiples; i++){
result += `${num} x ${i} = ${i * num}\n`;
};
return result;
}
console.log(showMultiples(2,8));

Constructing a URL from an array

I have an Array:
var arr[];
I have inserted many coordinates to this (x and y values)
arr[0]=12+'#'+32;
arr[1]=34+'#'+87;
arr[2]=90+'#'+89;
So when i print this array i get a string like ,12#32,34#87,90#89. These are coordinates. How do i break these and append this to a string which will be in the format.
http://host/app?x1=12&y1=32&x2=32&y2=87&x3=90&y3=89
This above URL can have many parameters. How can i construct the above URL from my array.
You can build your querystring looping through the array (here I used .each()) and using the .split() function to separate your coordinates.
var qs;
$.each(arr,function(i,v){
qs += "x" + i + "=" + v.split("#")[0] + "&y" + i + "=" + v.split("#")[1] + ((i+1)!=arr.length) ? "&" : "";
});
var url = "http://host/app?" + qs;
Similar to the above answers, loop through, split on the hash, add the pieces to the query string, and append the ampersand if you're not at the end.
for(var c = 0, query = "http://host/app?", coordinate; c < arr.length; c++) {
coordinate = arr[c].split("#");
query += "x" + (c + 1) + "=" + coordinate[0] + "&";
query += "y" + (c + 1) + "=" + coordinate[1];
if(c < arr.length - 1) query += "&";
}
The simplest approach I can think of is:
var arr = [12+'#'+32, 34+'#'+87, 90+'#'+89],
url = 'http://host/app',
params = [], temp;
arr.forEach(function (a) {
temp = a.split('#');
params.push('x=' + temp[0] + 'y=' + temp[1]);
});
url += params.join('&');
console.log(url);
var arr = [12+'#'+32, 34+'#'+87, 90+'#'+89],
url = 'http://host/app',
params = [], temp;
arr.forEach(function (a) {
temp = a.split('#');
params.push('x=' + temp[0] + 'y=' + temp[1]);
});
url += params.join('&');
console.log(url);
References:
Array.prototype.forEach().
Array.prototype.join().
Array.prototype.push().
String.prototype.split().

Replace last index of , with and in jQuery /JavaScript

i want to replace the last index of comma (,)in string with and.
eg . a,b,c with 'a,b and c'
eg q,w,e with q,w and e
DEMO
lastIndexOf finds the last index of the parameter string passed in it.
var x = 'a,b,c';
var pos = x.lastIndexOf(',');
x = x.substring(0,pos)+' and '+x.substring(pos+1);
console.log(x);
you can also use this function
function replace_last_comma_with_and(x) {
var pos = x.lastIndexOf(',');
return x.substring(0, pos) + ' and ' + x.substring(pos + 1);
}
console.log(replace_last_comma_with_and('a,b,c,d'));
An alternative solution using regex:
function replaceLastCommaWith(x, y) {
return x.replace(/,(?=[^,]*$)/, " " + y + " ");
}
console.log(replaceLastCommaWith("a,b,c,d", "and")); //a,b,c and d
console.log(replaceLastCommaWith("a,b,c,d", "or")); //a,b,c or d
This regex should do the job
"a,b,c,d".replace(/(.*),(.*)$/, "$1 and $2")
Try the following
var x= 'a,b,c,d';
x = x.replace(/,([^,]*)$/, " and $1");
Try
var str = 'a,b,c', replacement = ' and ';
str = str.replace(/,([^,]*)$/,replacement+'$1');
alert(str)
Fiddle Demo
A simple loop will help you out
first find the index of all , in your string using,
var str = "a,b,c,d,e";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === ",") indices.push(i);
}
indices = [1,3,5,7] as it start from 0
len = indices.length()
str[indices[len - 1]] = '.'
This will solve your purpose.

How to use join (in built method) in javascript?

In javascript loop i am generating a xml like this:
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
//s = s.join(' ');
}
Forgot about the t variable and all. by run this code i am getting the s value in the following format:
<row dc = "abc" al="56" msg="dkaj" />
In the second iteration it shows like this:
<row dc = "abwwc" al="56w" msg="dkajad" />
and so on till the m<t.length satisfy. What i want to join the list in each iteration. After joining all of them i should get in this way:
<row dc = "abc" al="56" msg="dkaj" /><row dc = "abwwc" al="56w" msg="dkajad" /> and so on..
I tried to do it with join written in comment section, but didn't work for me. What i am doing wrong?
The best way would be to define a string outside the loop an append to it;
var v = '';
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
v += s;
}
alert(v);
If you still want to use join(), make v an array and push() elements on to it (note that join() is an array method, not for string's)
var y = [];
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
y.push(s);
}
alert(y.join(''));
You'll be pleased to see I've tried to adhere to your variable naming conventions in my examples (i.e. meaningless characters).

Categories

Resources