storing values derived in a loop in javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Please I need you guys help. I want do some calculations on the values that will be obtained from a loop but the calculation will depend on the last value the loop will compute. How do I store these values until the last value is computed by the loop and use the outcome to do further calculation on the previous values. Please I need a demonstrating example

I'm not exactly sure what you mean, but you could store every single value from the loop like this:
//First, make an empty array.
var values = [];
//Then, make your loop. This loop runs 50 times, but
//you can make it run however many times you want.
for (var i = 0; i < 50; i++) {
//This is where your loop does something with "i".
//You can do whatever you want with it, but I've chosen to square it.
values[i] = i * i;
}
//Now, "values" is an array with every calculation from the loop.
//Make another for loop, where "i" counts up to the length of "values".
for (var i = 0; i < values.length; i++) {
//The last result of the first loop is values[values.length - 1].
//here, do what you want with the values. I have chosen to divide each
//value by the last calculation of the function.
values[i] = values[i] / values[values.length - 1];
}
Hope this helped.

Related

Javascript - Sum solution [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am getting below line in my source file and I would like to sum those values separated by pipe ("|")
There is no limit for the values coming in the line (might be 100 values)
10|20|30|40|[no limit for values] - Separator is pipe "|"
The ouptput would be 100
Please help to write a javascript function for the above query.
Regards
Jay
You should take a look at JavaScript's built-in functions: With split you can split your string into an array, with reduce you can 'reduce' your array to a single value, in that case via summation. These two links should provide you enough information for building your code.
You could try something like below:
function sum(value){
var total = 0;
var array = value.split(",").map(Number);
for( var i = 0; i < array.length; i++) {
total += array[i];
}
alert(total);
}
var value = "10|20|30|40".replace(/\|/g, ',');
console.log(sum(value));
https://jsfiddle.net/f7uqw7cL/

Insert n characters in the nth row using JavaScript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Given a number n and a character c, the task is to replace the innerHTML of an element with n rows of text. The first row should have one copy of c, the second row should have two copies of c, etc. <br> tags are to be inserted to separate each row.
I've been thinking that a nested for loop might be appropriate here, where the outer for creates the rows, and the inner for repeats the characters in each row, but just can't put it together in my mind, and not sure if that's even a good approach.
I am thinking something perhaps like:
for(i = 1; i <= n; i++) {
for(j = 1, j <= n; j++) {
document.getElementById("output").innerHTML = c;
}
document.getElementById("output").innerHTML += <br>;
}
Nested for loops typically have bad performance implications, but assuming you're doing this on a small scale, this should give you an idea of what to go for http://jsfiddle.net/mrodkc1u/1/
However, since the number of rows will be the same number of characters in the largest row, you shouldn't need to use a nested loop. Here's an updated fiddle with just one loop http://jsfiddle.net/mrodkc1u/2/

How do I rearrange an array with similar items so that similar items will never neighbor each other? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So for example if I have this array:
var input = [1,1,2,4,6,7,7,1];
I want the output to be something like:
[1,2,1,4,6,7,1,7]
The order of the new array does not matter, as long as similar items will never (or at least as seldom as possible) neighbor each other.
I can use plain JavaScript as well as underscore.js.
Try the following:
var input = [1,1,2,4,6,7,7,1];
input.sort()
var output = [];
var len = input.length;
for (var i = 0; i < Math.floor((len / 2)); i++) {
output.push(input[i]);
output.push(input[len - i - 1]);
}
if (len % 2) {
var left_over = input[Math.floor(len / 2)];
if (left_over == output[0]) {
output.push(left_over);
} else {
output.unshift(left_over);
}
}
Or see http://jsfiddle.net/d0j3Lfa3/1.
The solution sorts the numbers then alternates high and low. It deals with an odd number of elements, including corner cases such as [1,1,2] and [1,2,2] where it needs to push the middle element differently to pass. Since the input is sorted, input order doesn't affect the output.
This answer may help simplify things a bit.

Check if value range is in array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
What: I have an array that has angles from 0 to 360, a predefined range is entered, and a periodically updating input ranging from 0 to 360. I want to check if the input is within the the predefined range of the array.
Example
array:
array[0]=100, array[1]=40, array[2]=320, array[3]=60, etc....
What I need to do is to see if the input lets say
input:
input=50;
is within a range of any of the values in the array
range:
range=25;
What I need code to do:
lower range = input-range & upper range = input+range
if values between the lower range and upper range exist in the array output the array number.
Completing the example: input-range=25 & input+range=75
so if a value between 25 & 75 exist in the array
array[1]=40 & array[3]=60 are within that range.
output the array key:
output[0]=1, output[1]=3
Approach:
Create a new nested array with the range added to and subtracted from the value in each array component. Then a for loop to check if the input is within any of the values.
Example Solution:
var nodeArray=new Array();
for(var i = 0; i<array.length;i++){
nodeArray[i].push(array[i]-range);
nodeArray[i].push(array[i]+range);
}
then the function to check:
for(var j=0;i<array.length;i++){
if ((input>nodeArray[j][0])&&(input<nodeArray[j][1])){
alert("within range");
}
}
Problem: I need a fast executing solution as time of execution is important to me and Im just curious if someone has a much improved idea on how to solve this problem.
Note: I also have not solved the fold over problem(350deg + 20 deg = 10 deg)
I found three optimisations
First : Don't use the function length in your loop, because the function is called each time. Declares a new variable and save the array length inside :
for(var j=0, arrayLength = array.length; j < arrayLength ;j++){}
Second : If you just need to know if one value is within the range, use break in your requirement if to exit the loop 'for':
if ((input>nodeArray[j][0])&&(input<nodeArray[j][1])){
alert("within range");
break;
}
Third: You can change the way to write the for loop.
for(var i = -array.length; i++ ;){}
Like that you remove one variable declaration and one operation of comparison.

Increase performance for array manipulation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am using as certain code in JavaScript where I have to append a huge amount of data such as 10000 objects at a time to an array, and in a click event I again empty that array and reload that array with 10000 objects. Here is my code snippet:
where "Nodes" is an array populated from user datasource.
var Index = 0;
var _array = new Array();
for (var i = 0; i < this.Nodes.length; i++) {
if(this.Nodes.PLeft>this.Nodes.Cleft){
var temp = {};
temp["PLeft"] = this.Nodes.PLeft;
temp["CLeft"] = this.Nodes.CLeft;
temp["PWidth"] = this.Nodes.PWidth;
temp["CWidth"] = this.NodesCWidth;
temp["PTop"] = this.Nodes.PTop;
temp["CTop"] = this.Nodes.CTop;
temp["Height"] = this.Nodes.Height;
_array[Index++] = temp;
}
}
This works fine with Firefox, but for IE and Chrome the performance is too bad -- sometimes the browser crashes. I have also used push() method for array, but I did not find much difference in the performance. Does anyone have any idea on how to improve performance of array manipulation?
A few issues here. First, your loop does not access the individual elements of this.Nodes. Because you keep referring to this.Nodes.PLeft (for example), you wind up with the same probably-undefined value. You must specify the index, this.Nodes[idx].PLeft.
This, of course, begs the question: why do you need to loop some array and turn it into... an array? Can't you just use this.Nodes directly instead of transferring it all into _array first?
Another thing: to reduce the weight of a loop, get the max length outside of the loops conditional statement. Doing it within the conditional causes that value to be looked up every time, by putting it into a variable the lookup only happens once.
You can eliminate the temp object and add the new array element directly. Likewise, you can eliminate the redundant counter and use the for... loop's counter.
var _array = [];
var maxlen = this.Nodes.length;
for (var idx = 0; idx < maxlen ; idx++) {
if(this.Nodes[idx].PLeft > this.Nodes[idx].Cleft){
// use idx for the array key IF you want it to match with this.Nodes indexes
// if you don't care, use _array.length
_array[_array.length] = {
'PLeft':this.Nodes[idx].PLeft,
'CLeft':this.Nodes[idx].CLeft,
'PWidth':this.Nodes[idx].PWidth,
'CWidth':this.Nodes[idx].CWidth,
'PTop':this.Nodes[idx].PTop,
'CTop':this.Nodes[idx].CTop,
'Height':this.Nodes[idx].Height
};
}
}

Categories

Resources