Jquery loop compare not getting expected result [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is my code. I will explain everything step by step :
myobj ={ month: 1, total: 2 }{ month: 3, total: 1 }
newArray = [];
for(i=0;i<=5;i++){
$.each(myobj.function(k,v){
if(i==v.month){
newArray.push(v.month)
}else{
newArray.push(0)
}
})
}
After what I am getting is : 1,0,0,0,0,3,0,0,0,0
expected output : 1,0,3,0,0
I don't know what I am missing here. Can anyone please help me related this? I am stuck here

Your inner loop is pushing onto the new array for every item in the array, not just if the desired month is found.
Don't use an inner loop. Use find() to find the matching month, and push 0 if you don't find it.
for (i = 1; i <= 5; i++) {
if (myobj.find(el => el.month == i)) {
newArray.push(i);
} else {
newArray.push(0);
}
}
if you want to push the totals instead of the months, assign the result of find() to a variable so you can get the total from it.
for (i = 1; i <= 5; i++) {
var found = myobj.find(el => el.month == i);
newArray.push(found ? found.total : 0);
}

Related

How to detect sign toggle in javascript array? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have example of javascript array as below.
var exampleArr1 = [5,4,1,-2,-5,-7,5,1,2,-3,2,4...];
var exampleArr2 = [-5,-4,1,2,5,7,-5,1,2,3,-2,4...];
I would to create function to detect sign change and return with position, e.g. ['index','num1','num2'] For example.
function getSignChange(exampleArr1){
...
return someArray;
}
return shoud be
[
[2,1,-2], //index = 2 change from 1 to -2
[5,-7,5], //index = 5 change from -7 to 5
[8,2,-3], //index = 8 change from 2 to -3
]
Any advice or guidance on this would be greatly appreciated, Thanks.
Maybe this will help you:
var exampleArr1 = [5,4,1,-2,-5,-7,5,1,2,-3,2,4];
var exampleArr2 = [-5,-4,1,2,5,7,-5,1,2,3,-2,4];
function getSignChange(arr){
let positive = arr[0] >= 0;
return arr.map((item, index) => {
if (positive && item < 0 || !positive && item >= 0) {
positive = arr[index] >= 0
return [index-1, arr[index-1], item]
}
}).filter(x => x != null);
}
console.log(getSignChange(exampleArr1));
console.log(getSignChange(exampleArr2));

I need to sort out this algorithm [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
could you please your help.
how to answer this question ?
I need your help thinks
function factorial(n) {
if (n === 0) {
return 1;
} else {
return n * n ;
}
}
factorial(6)
this is not right.. i need to use writing code with Loop javascript.
Get the factorial of n. The inheritance of n is the number 1 through n multiplied by all numbers.
example)
answer should be like this
factorial(4); // => 24
factorial(5); // => 120
One way is to use a simple for loop.
var answer = 1;
for(var i = 2; i <= n; i++)
{
answer *= i;
}
return answer;
You can also do this recursively by multiplying your input by the result of the previous value.
function factorial(n){
if(n <= 1) return 1;
return n * factorial(n-1);
}

Iterate two arrays: Cannot read property 'length' of undefined [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I want to iterate over two arrays, states and districts, but I get an error-message saying "Cannot read property 'length' of undefined". I don't know what's causing it.
This is my code:
var estados = [ "aguascalientes", "baja-california", "baja-california-sur",
"yucatan", "zacatecas", ];
var municipios = [ [ "aguascalientes", "asientos", "calvillo", "cosio", "tepezala" ],
[ "mexicali", "playas-de-rosarito", "ensenada" ] ];
$("#property_location").change(function () {
$( "#property_location option:selected" ).each(function() {
var i;
var j;
for (i = estados.length - 1; i >= 0; i--) {
if ($( this ).val() == estados[i]) {
console.log(estados[i]);
for (j = municipios[i].length - 1; i >= 0; i--) {
$("#property_municipio option[value='"+municipios[i][j]+"']").show();
}
} else {
for (j = municipios[i].length - 1; i >= 0; i--) {
$("#property_municipio option[value='"+municipios[i][j]+"']").hide();
}
}
}
});
}).change();
Your problem is that estados has more member than municipios you loop trough every member of estados and check how many member does the municipios sub array have.
for (j = municipios[i].length - 1; i >= 0; i--)
if i is greater than 1 municipios[i] is undefined and you can't calculate the length of undefined. this generate your error.
By the way, you overwrite your loop index i if you use it in both loops.
Please use it like that:
for(var i = 0; i < array.length; i++){
...
for(var j = 0; j < array.length; j++){
...
}
}
The first/top array is having 5 elements as I see, while the second array municipios is having 2 elements( ofcourse the nested lists are having data, but the actual length will be 2 as is it containing only 2 lists).
While the outer loop is working fine, the issue is with the inner loop. When i reaches greater than 2, suppose 3, the code is trying to fetch the 3rd element from municipios array, which does not even exist. Moreover, its trying to access that particular elements' length.

Parse.com Overwrites my results when Javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm not sure what am I doing wrong.
When running the attached code I would expect to see 100 rows inside Parse.com.
Instead, I only see only one.
For some reason, Parse.com is overwriting the same line 100 times.
And ideas? :/
Me.
function simplewrite() {
Parse.initialize("********************, ***********************");
var Numbers = Parse.Object.extend("Numbers");
var numbers = new Numbers();
for (var i=0; i<100; i++) {
numbers.set("number", i);
numbers.save(null, {
success: function(numbers) {
console.log("YES " + i);
},
error: function(numbers, error) {
console.log("no! " + i);
console.log(error);
}
}); // End
};
};
Your for loop is updating the same numbers variable over and over. Try moving the initialization of numbers to inside your for loop:
// ...
for (var i=0; i<100; i++) {
var numbers = new Numbers();
// ...

Change var values = [2, 3, 4] to something like [all whole numbers] [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here's a another noob question.
Again working with YUI3.
How can I change:
var values = [2, 3, 4];
to include ALL whole numbers, and not just 2, 3, and 4 ?
Thanks!
EDIT:
Here's a bit of extra info.
This is what I have:
var numbers = [2, 3, 4];
for(var i = 0; i < numbers.length; i++)
{
var boxnum = numbers[i];
Y.all(".box"+boxnum ).addClass(boxnum );
}
so just want to check for each possible class of . box1, .box2, .box3, .... ,but I'm not sure how many of these classes there might be.
Ta!
To Find all elements with class "box" + x:
for (var x = 0; x <= 9999; x++) {
if ($('.box' + x).length < 1) {
$('.box' + x).addClass('yourClass');
} else {
break;
}
}
This assumes you wont have box x if you don't have box (x-1). (boxes are numbered in order without any missing numbers) If this assumption is not correct, let me know.
for some reason I would not recommend looping through and calling the jQuery function 1000 times, I would recommend you call it once. Something like this perhaps
var elements = $('*').filter( function() {
return /box[0-9]/.test( this.className )
});
Demo: http://jsfiddle.net/qjVsU/
Benchmarks: http://jsperf.com/class-starts-with-selector-jquery

Categories

Resources