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
};
}
}
Related
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 last year.
Improve this question
The goal of this code is to double each number in the array. I was trying to mimic the map() method. But that is not important. What I am wondering is why this code gives me an output of 5 while I did not console.log it. Then when I run it again it keeps adding 5 to a variable I am not aware of?
const numbers = [1, 2, 3, 4, 5];
const doubleNumbers = [];
for (let i = 0; i < numbers.length; i += 1) {
doubleNumbers.push(numbers[i] * 2)
}
It is because Array.push returns the new length of the array:
let arr = [];
console.log(arr.push('something')) // Should output 1
console.log(arr.push('something else')) // Should output 2
You didn't log anything, but if you run code in the console it will print the outcome of the last statement.
From the documentation: the push() method adds one or more elements to the end of an array and returns the new length of the array.
If you run this in the developer console, it will log the last returned result.
Your Code output is okay
const numbers = [1,2,3,4,5];
const doubleNumbers = [];
for (let i = 0; i < numbers.length; i+=1) {
doubleNumbers.push(numbers[i] * 2)
}
console.log(doubleNumbers)
Maybe You console the length of array
Maybe you aren't giving the entire context here?
What is numbers2 anyway? You declare a new array, doubleNumbers, but don't use it?
doubleNumbers.push(numbers[i] * 2)
should work just fine I believe.
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.
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.
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.
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 8 years ago.
Improve this question
My Structure of data will be like below
var data = {"Questions" : [
{"QID":"Q1","S":"2"},
{"QID":"Q2","T":"12"},
{"QID":"Q3","U":"22"}], // Also please suggest me to improve this to make parsing easier
"Share" : "Yes"
};
for(var item in data.Questions)
{
if(this.QID == "Q2") // this.QID returns me undefined
{
// I want to retrieve the total object i.e
// {"QID":"Q2","T":"12"} should be returned
}
}
Why does this.QID return me undefined? How can I retrieve the total object, i.e. {"QID":"Q2","T":"12"}?
Don't iterate Arrays using for .. in loops. Use a regular for loop or Array.forEach()*.
That aside, this is not going to be an item in your Array. You need:
if (data.Questions[item].QID == "Q2") {
...
}
Using a regular for loop:
for (var i = 0; i < data.Questions.length; i++) {
if (data.Questions[i].QID == "Q2") {
...
}
}
Or, my preferred method, Array.forEach():
data.Questions.forEach(function (item) {
if (item.QID == "Q2") {
...
}
});
*Older browsers don't natively support Array.forEach(), but you can add it in yourself. See the compatibility notes for an implementation you can use in your code for older browsers.
Change your iteration code to this:
var questions = data.Questions;
for (var i = 0; i < questions.length; i++) {
if (questions[i].QID == "Q2") {
// questions[i] is all the data of this array element
}
}
Arrays should NOT be iterated with for (x in array). That type of iteration iterates over object properties which will also pick up array elements, but it's not recommended. Use array indexing or .forEach() in a modern browser to iterate through an array in a predictable order and without any other properties showing up in the iteration.
In addition, the way you were trying to do the iteration does not set this to anything so you can't use it to access the array element.