How to use join function to sum 2 fields in JavaScript - javascript

Can someone help me to sum the 2 fields and display the results in one box by using JavaScript.
var values1 = this.getField("Text6").value.split("\r");
var values2 = this.getField("Text7").value.split("\r");
for(i = 0; i < values1.length ; i++)
{
values1[i] = parseInt(values1[i]) + "\n";
values2[i] = parseInt(values2[i]) + "\n";
this.getField("Text8").value = (values1[i]+values2[i]).join("") ;
}
I am getting the following error:
TypeError: (values1 + values2).join is not a function

You can't join like that, the join method can only be applied on an array.
You can do this:
this.getField("Text8").value = [values1[i], values2[i]].join("");
But a better way:
this.getField("Text8").value = `${values1[i]}${values2[i]}`;
EDIT:
If you want to do a sum, you can simply do this:
this.getField("Text8").value = values1[i] + values2[i];
If you have string instead of a int as values, then you need to cast their values before:
this.getField("Text8").value = parseInt(values1[i]) + parseInt(values2[i]);

Related

How to format the element inside an array?

I have three arrays for example:
var name = ["wheel", "rectangle", "moon"];
var type = ["car", "shape", "sky"];
var all = [];
var temp = " ";
for (var i = 0; i < name.length; i++) {
temp = name[i] + " " + type[i];
all.push(temp);
}
for (var i = 0; i < name.length; i++) {
// I call here function to display all element of array `all`
}
The output is:
wheel car
rectangle shape
moon sky
But the format of output is not nice. I want to shift the element of array type before add them to array all, so I want the output to be like:
wheel car
rectangle shape
moon sky
My question is: how can I shift elements of the array to add them to another array and store them in a way that allows to me to display the elements like form above ?
But the form of output not nice
If you simply want to format the output in a better way, then try console.table
var name1 = [ "wheel","rectangle","moon" ];
var type = [ "car" , "shape", "sky"];
var all=[];
for (var i = 0; i< name1.length; i++)
{
all.push({ name : name1[i], type: type[i] });
}
console.table(all);
Try this fiddle to see the actual output since stack-snippet alters the behaviour of console api
You should calculate which is the longest string in the first array so to know in advance how many spaces you need to append to correctly pad the string
var n = ["wheel", "rectangle", "moon"];
var t = ["car", "shape", "sky"];
var all = [];
/* sorting the values of the first array by length desc,
* then get the length of the first element
*/
var padding = n.sort(function(a, b) {
return a.length <= b.length;
})[0].length + 1;
n.forEach(function(el, i) {
all.push(el + " ".repeat(padding - el.length) + t[i]);
});
Output
"rectangle car"
"wheel shape"
"moon sky"
codepen demo
First loop over the array and find the max length. Then loop again and add spaces.
<script >
var name=["wheel","rectangle","moon"];
var type=["car","shape","sky"];
var all=[];
var i=0;
var maxLength=0;
string temp=" ";
String.prototype.padLeft= function(len, c){
var r = '';
while(r.length < len) r += c;
return s+r;
}
for (i = 0; i< name.length; i++)
{
maxLength = Math.max(maxLength, name[i].length+type[i].length+1;
}
for (i = 0; i< name.length; i++)
{
temp=name[i]+type[i].padLeft(maxLength-name[i].length-type[i].length);
all.push(temp);
}
</script >
I would do as follows;
var id = ["wheel","rectangle","moon"],
type = ["car","shape","sky"];
id.longestStringLength = Math.max(...id.map(s => s.length));
type.longestStringLength = Math.max(...type.map(s => s.length));
id = id.map((s,_,a) => s + " ".repeat(a.longestStringLength-s.length));
type = type.map((s,_,a) => " ".repeat(a.longestStringLength-s.length) + s);
console.log(id,type);
Use \t instead of space while concatenating to make it aligned.
Why don't you just add tab '\t' and it will give you the desired output. Or you can append fixed number of spaces between the two array items.

Get max value of similar items in array with Javascript

I have an array like this:
["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"]
and I want to get a final array that will group similar values that changes from each other only by the last numbers of the string ("13rq8", "13rq6", "13rq4", "13rq2", "13rq12", "13rq10"), and return only the biggest values like the example below:
["13dl", "12dl", "13rq12"]
Can you help me please resolve this in Javascript?
Thank You!
Use an object (ex. tagNum) to keep track of the largest value of each prefix, and use regular expression to extract the prefix and trailing value:
var l = ["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"];
var tagNum = {};
l.forEach(function(x) {
var m = x.match(/^(.*?)(\d*)$/);
var tag = m[1];
var num = parseInt("0" + m[2]);
if (tagNum[tag] === undefined || tagNum[tag] < num) tagNum[tag] = num;
});
var l2 = [];
for (var tag in tagNum) {
var num = tagNum[tag];
if (num) l2.push(tag + num);
else l2.push(tag);
}
console.log(l2);

How to most efficiently generate string from array of objects in javascript?

I have the following:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}]
I want to generate a string like this:
"Jordan,6|Jake,7|Mark,10"
What is the most efficient way to do this?
I am currently using:
var studentstr = "";
for(var i = 0; i < students.length; i++) {
studentstr = students['name'] + "," + students['age'] + "|"
}
studentstr = studentstr.substring(0, studentstr.length - 1);
Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation? The resulting string contains both keys in the object and not a single join on one object in the property.
You can map each student object to a string and then join them all with |:
var studentstr = students.map(function (student) {
return student.name + ',' + student.age;
}).join('|');
Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation?
No.
Yes, using string concatenation in a loop is costly. The string grows for each iteration, and each time you have to copy the entire previous string to create the new version. The execution time of the loop grows exponentially to the number of items.
You can put the string for each object in an array, then join them together:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}];
var items = [];
for (var i = 0; i < students.length; i++) {
items.push(students[i].name + ',' +students[i].age);
}
var str = items.join('|');
// display result in snippet
document.write(str);
map works well for this:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}];
var result = students.map(function(student) {
return student.name + ',' + student.age;
});
alert(result.join('|'));
Try this and see your console:
var string = '';
for (var s in students) {
string += students[s].name + ', ' + students[s].age + ' | ';
}
console.log(string);
Fiddle: http://jsfiddle.net/80ss0u14/
I do not think it is costly to go on with such approach. It may be the most efficient way to iterate through the data.

Javascript: using a for statement as a variable

I'm fairly new to javascript and something I've been playing with lately is the 'for' statement. I'm questioning one thing, though. I've learned how to make a 'for' statement do things as if it was an output, like this:
for (i = 0; i < 3; i++) {
console.log(i);
}
But what if you want to set a variable for the whole output of the 'for' statement?
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
for ( i = 0; i < destinationArraySet; i++) {
console.log(destinationArray[i]);
} /*the whole thing should be equal to var destination */
var userDestinationPrompt = ("Where would you like to go? Available places: " +
/* var destination */
+
".").toUpperCase();
To give some more context: I'm making a game that allows further destinations when the destination before is cleared. Once that's achieved, I set destinationArraySet to a higher value, which means that more places would be logged and put after 'Available places'.
Help would be very appreciated! If there's something not clear enough let me know.
The for statement is not an expression, so it doesn't have a return value. Use a variable to collect values in the loop:
var destination = '';
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + ' ';
}
Of course, if you only want to concatenate the values in part of an array, you can use the slice method to get part of it, then the join method:
var destination = destinationArray.slice(0, destinationArraySet).join(' ');
var destination = '';
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + '\n';
}
console.log(destination);
Try this -
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
var availablePlaces = '';
var separator = '';
for ( i = 0; i < destinationArraySet; i++) {
availablePlaces += separator + destinationArray[i];
separator = ', ';
}
var userDestinationPrompt = ("Where would you like to go? Available places: " +
availablePlaces + ".").toUpperCase();
The for statement doesn't have an "output", it's not a function. Thinking for as a function will give you troubles later on. for is simply a statement that continuously execute the block of code inside. It does not "output", or in other words, return any value.
Do this instead:
var destinationArray = ["town", "areas", "bosses"], destinationArraySet = 1;
var userDestinationPrompt = ("Where would you like to go? Available places: " +
destinationArray.slice(0, destinationArraySet).join("\n")
+ ".").toUpperCase();
prompt(userDestinationPrompt);
Demo: http://jsfiddle.net/7c2b9q7m/1/
destinationArray.slice(0, destinationArraySet): Cuts the array to the specified length.
.join("\n"): Join the newly created array by \ns (newline) to micic the default console.log behavior.

adding multiple values to single array item in javascript

I am having trouble with output of an array, I think.
What I would like the output to look like is:
1. FirstName LastName DOB
but what I end up with is:
1. FirstName
2. LastName
3. DOB
Here is what I have so far but I am not seeing what I am doing wrong.
// global variable:
var tasks = [];
// Function called when the form is submitted.
// Function adds a task to the global array.
function addTask() {
'use strict';
// Get the task:
var firstName = document.getElementById('firstName');
var lastName = document.getElementById('lastName');
var dob = document.getElementById('dob');
// numerical value of dob
var dateofBirth = new Date(dob.value);
// Reference to where the output goes:
var output = document.getElementById('output');
// For the output:
var message = '';
if (firstName.value && lastName.value && dob.value) {
// Add the item to the array:
tasks.push(firstName.value, lastName.value, dateofBirth.toString());
// Update the page:
message = '<h2>Persons Entered</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
message += '<li>' + tasks[i] + '</li>';
}
message += '</ol>';
output.innerHTML = message;
} // End of IF.
// Return false to prevent submission:
return false;
} // End of addTask() function.
// Initial setup:
function init() {
'use strict';
document.getElementById('theForm').onsubmit = addTask;
} // End of init() function.
window.onload = init;
Thanks, I hope this helps you to help me.
tasks.push({firstName: firstName.value, lastName: lastName.value, DOB: dateofBirth.toString()})
And then
tasks[0].firstName will output firstName.value
tasks[0].lastName will output lastName.value
etc..
Edit
Using this, you can then construct your messasge like this :
for (var i = 0, count = tasks.length; i < count; i++) {
message += '<li><span>' + tasks[i].firstName + '</span><span> '
+ tasks[i].lastName + '</span><span>' + tasks[i].DOB + '</span></li>';
}
Of course, the span tags are optionnal but this will allow you to apply a style to each part of the information in your css (width, padding, etc..) and you will always be able to easily select a property of a task by index
Your problem is that you're adding li elements to every element in your array, instead only add teh li once
// Update the page:
message = '<h2>Persons Entered</h2><ol><li>' + tasks.join(' ') + '</li></ol>';
output.innerHTML = message;
Why do you put each element in its own <li>?
If you don't put it in different <li> but in a common one, everything will be fine
message = '<h2>Persons Entered</h2><ol><li>';
for (var i = 0, count = tasks.length; i < count; i++) {
message += tasks[i];
message += " ";
}
message += '</li></ol>';
output.innerHTML = message;
Use Span. you can use Array.join
output.innerHTML= '<h2>Persons Entered</h2><div><span>' + tasks.join("</span> <span>") +"</span>";
You want to add them as an array to the array, not as values to the array
What you have is this:
tasks.push(firstName.value, lastName.value, dateofBirth.toString());
what I think you want is this:
tasks.push([firstName.value, lastName.value, dateofBirth.toString()]);
The answer above is the same, but with an object, not a array.
What you are doing is pushing multiple values into your array. What you want to be doing is to turn the different values into a single value and then push that value into your array. To get the exact output as you were requesting, you can turn these multiple values into one by concatenating them into a string:
Change this:
tasks.push(firstName.value, lastName.value, dateofBirth.toString());
Into this:
tasks.push(firstName.value + ' ' + lastName.value + ' ' + dateofBirth.toString());
However, this does mean you'll lose access to the individual values. If you want access to those, you could instead assemble them into an object:
tasks.push({"firstName" : firstName.value,
"lastName" : lastName.value,
"dateOfBirth" : dateofBirth.toString());
Its a little confusing what you are asking. If you simply want this:
1. FirstName LastName DOB
over this:
1. FirstName
2. LastName
3. DOB
Then your issue is not with the array but with how you are defining the loop code. Try this instead:
// Update the page:
message = '<h2>Persons Entered</h2><ol><li>';
for (var i = 0, count = tasks.length; i < count; i++) {
message += tasks[i] + ' ';
}
message += '</li></ol>';
That way you are putting the array elements in a single list element, rather than across three of them.
EDIT - for Multi-dimensional array traversal
This is assuming that the array is defined this way (per Dan Steingart's answer):
tasks.push([firstName.value, lastName.value, dateofBirth.toString()]);
We then can have the following:
// Update the page:
message = '<h2>Persons Entered</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
message += '<li> + tasks[i].toString().replace(',',' ') + '</li>';
}
message += '</ol>';
Here you are traversing each element of tasks when each element of tasks is also itself an array. The toString() on an inner array will display the values in a comma separated fashion, then the replace() function simply replaces the comma's with spaces.

Categories

Resources