JS array being overwritten by bolean values when being read - javascript

First time around here, and I'm an awful dev, so forgive in advance my possibly numerous mistakes :)
here's my issue: I'm trying to make a program that checks the proportions of each number from 1 to 9 in an array (I'm putting Benford's Law to the test), for that I have created 9 different variables (basically nX where X=1-9), I'm reading through my array with a for loop, and incrementing on each of my variables every time that the corresponding number is found (if array[i]= X, nX++), and I then console log my array. The issue is that on that console log, all values in my array are set to "1", which isn't the case prior to the execution of these few lines. So I'm not quite sure what happens, but I'm guessing that my "if" checks are returning "true" and changing the value of my array elements to 1 to reflect that.
So my question would be: any of you wise wizards know what I'm doing wrong and how to keep my data from being corrupted by this operation?
here's some code:
for (i = 0; i < benfordArrayProcessed.length; i++) {
if (benfordArrayProcessed[i] = 1) {
n1++;
} else if (benfordArrayProcessed[i] = 2) {
n2++;
} else if (benfordArrayProcessed[i] = 3) {
n3++;
}
[...]

In your expression, you need use boolean expression instead of assignment, e.g. if (benfordArrayProcessed[i] == 1). The values in the error get overwritten with because of assignment int he first statement itself and that's the reason you see 1 for all the elements.

Apart from the == usage, you can also chose to go for a switch statement:
for (i = 0; i < benfordArrayProcessed.length; i++) {
switch (benfordArrayProcessed[i]) {
case 1:
n1++;
break;
case 2:
n2++;
break;
case 3:
n3++;
break;
[...]
}
}
Or, use an object with keys to up the numbers (a bit more tricky and depending on how you want to implement the rest of your code):
const n = {
1: 0,
2: 0,
3: 0,
};
for (i = 0; i < benfordArrayProcessed.length; i++) {
const num = benfordArrayProcessed[i];
n[num]++;
}

Related

Apps Script For Loop stuck at 0 in iteration although it is running

I have an array 'vnData' containing 5, 6 rows from where I am trying to extract 3rd column values (based on a criteria) and insert to a new array. Here is my code
for (odr = 0; odr < vnData.length; odr++){
Logger.log(vnData);
tempOdr = vnData[odr][3];
Logger.log(odr);
Logger.log(tempOdr);
Logger.log(vnData[odr][3]);
for(k = 0; k < vnData.length; k++){
if(vnData[k][3] = tempOdr){
odrVal = odrVal + vnData[k][11];
}
}
if(odrVal > 0){
affOdrSet.push(tempOdr);
}
Logger.log(affOdrSet);
}
Logger gives right value of odr in Logger.log(odr); but in Logger.log(vnData[odr][3]); I am always getting a result where value of odr is 0.
So for each iteration I get value from first row. Please help what is wrong in it.
One more thing, if I log Logger.log(vnData[3][3]) in place of Logger.log(vnData[odr][3]) then for first iteration it gives me right value from row 4 but for all subsequent iterations even Logger.log(vnData[3][3]) gives value from first row which is really weird.
The problem is the expression of the first if statement. Instead of
vnData[k][3] = tempOdr
use
vnData[k][3] === tempOdr
The above because = is the assign operator but it's very likely that instead of assigning tempOdr to vnData[k][3] what you want to compare them.

Is there an alternative to console.log() which lets you print out and update a single line instead of spamming the console?

I am looking for a way to print out a given variable f.ex. the i of a for-loop for each iteration, without it resulting in the entire console being filled with new lines of new values. Is there a console. method for just printing one line, and updating that as we go?
I realise that you could do this by implementing a text-field in your program which you change the with each iteration, but if there is a way of doing this in the console it would be a bit easier (and perhaps quicker? although I am really not sure about that). Thanks in advance.
If there is still confusion about what im asking, what i want is my console to print out:
"i = " i once, and then update the i in that one line, instead of:
i=1
i=2
i=3
1=4
.
.
.
which gets really messy as you go. For the exact example of the i in a for loop, you could get this value from just console.log()'ing the same thing for each iteration, and a number will pop up beside it (in firefox anyway), but i would like to be able to do this with some more useful information.
Option 1: use console.groupCollapsed() and console.groupEnd():
console.groupCollapsed();
for (let i = 0; i < 100; i+= 1) { console.log(`i = ${i}`) }
console.groupEnd();
Option 2: set the values in an array or a string and log the var when the iterations finish:
let valuesToLog = [];
for (let i = 0; i < 100; i+= 1) { valuesToLog.push(`i = ${i}`) }
// see it as an array
console.log(valuesToLog);
// see it as a string, with each value separated by ', '
console.log(valuesToLog.join(', '));
how about JQuery console.clear()?
$(function(){
loop_counter();
});
function loop_counter() {
for (let i = 1; i <= 100; i++){
console.clear();
console.log ("i=", i)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

javascript if else for beginners

I am very new to Javascript, so I am having a hard time figuring out this easy exercise and what I'm doing this wrong. Any help would be greatly appreciated!
You are given two numeric variables: var n = 25; var result = 0;
Their values may change when you submit.
DO NOT EDIT CODE ABOVE THIS LINE.
=================================
Your Challenge:
Using if and else, make decisions based on the values
of n and result with the following rules:
1. When n is even,
set the value of result to result's current value
plus 10.
2. When n is odd,
set the value of result to result's current value
minus the value of n.
3. Do not declare new variables.
4. Be sure your solution works for all values of n and result.
if (n%2 == 0) {result+10;} else {result-n;}
Your problem isn't if/else, the problem is you never set result to the new value. result+10 just results in the value without storing that value anywhere. (In many programming langauges, that would be a syntax error, but JavaScript allows what it calls ExpressionStatement where any expression can be a statement.)
Either use the compound assignment operators (+= and -=), or write a verbose assignment (result = ...).
Side note: It's easier to debug and edit code when statements are on their own lines, suggest:
if (condition) {
trueStuffHere
} else {
falseStuffHere
}
...or any of the several variations on that theme where trueStuffHere and falseStuffHere are on lines of their own.
You may set the result?
if (n%2 == 0) {
result = result + 10;
} else {
result = result - n;
}
Or if you're a bit better:
if (n % 2 == 0) {
result += 10;
} else {
result -=n;
}

How can I optimize a for-loop over a list of specific conditions?

I've got a for-loop in JavaScript, iterating over the variable i. In each iteration step, a list of if-conditions is checked. For each i, only one of these conditions can be true (or none of them) and every condition is true for exactly one i. A very simple example would be:
for (i = 1; i <= 10; i++)
{
if (i === 3) {some code ...}
if (i === 7) {some other code ...}
}
So obviously for 4 <= i <= 10 the condition i === 3 will always fail. Is there a way to achieve that if a condition is true for some i, this condition will not be checked any more for the other i's? Can this condition be deleted in some way? This would make the loop much faster.
(Of course the example of above does not make much sense and the real use case is much more complicated.)
Thank you in advance for your help!
Switch is better for what you're trying to achieve
for (i = 1; i <= 10; i++)
{
switch(i){
case 1:
some code..;
break; //once this is called, the statement will stop
case 3:
some other code..;
break;
}
}
You can use else if statements to skip all of the other conditions once one is found.
for (i = 1; i <= 10; i++) {
if (i === 3) {some code ...}
else if (i === 7) {some other code ...}
}
In this case, if i is 3, the other conditions will be skipped.

Eloquent javascript ch4: How does indexOf() work? (Data-structures- Objects&Arrays)

http://eloquentjavascript.net/04_data.html
Please. Scroll down to the headline "The lycanthrope’s log" . It introduces the phi correlation which took me a while to understand, If you scroll down a little bit further, You will find the headline Computing correlation.
var journal = [];
function addEntry(events, didITurnIntoASquirrel) {
journal.push({
events: events,
squirrel: didITurnIntoASquirrel
});
}
function phi(table) {
return (table[3] * table[0] - table[2] * table[1]) /
Math.sqrt((table[2] + table[3]) *
(table[0] + table[1]) *
(table[1] + table[3]) *
(table[0] + table[2]));
}
Top^^^^The code that is also part of the full "program". I've put my "QUESTIONS" in comments in the code below. Please help! If anyone can also answer the comments in my question i will be VERY GRATEFUL!!!!!
function hasEvent(event, entry) {
return entry.events.indexOf(event) != -1;
/*What does "events" do?Why -1?How does indexOf work?"*/
}
function tableFor(event, journal) {
var table = [0, 0, 0, 0];
/*How does the program figure out each of the values for this table?*/
/*and how does it know when one value ends and the time to start*/
/*calculating the next value*/
for (var i = 0; i < journal.length; i++) {
var entry = journal[i], index = 0;/*???? why 0*/
if (hasEvent(event, entry)) index += 1;
/*I dont understand how this function works*/
if (entry.squirrel) index += 2;/*why +2?*/
table[index] += 1;/*what exactly is index???*/
}
return table;
}
I'm really new to teaching myself programming. Eloquent javascript is supposed to be for beginners and i'm already struggling :\
indexOf is a method available on Strings and Arrays in Javascript. You can use it to find something in either one of the objects. It returns -1 if it doesn't find the thing you're looking for in the String or Array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
return entry.events.indexOf(event) != -1; Is trying to figure out if the event you're asking about, exists within the array of events for a given entry by checking the return value of indexOf. This is a common Javascript idiom.
var entry = journal[i], index = 0;/*???? why 0*/
this assigns a reference to value from journal[i] into the entry variable. It also assigns the integer value 0 the index variable.
This multiple variables being defined on a single line. How to define multiple variables on a single line?
This is an if statement that only executes the code directly following it. This is terrible, but valid, syntax. You should never do this in real life. Always use braces. if (hasEvent(event, entry)) index += 1;
Are curly braces necessary in one-line statements in JavaScript?
I've transformed the code you posted into something more readable by getting rid of all the syntactic junk the author put in there. My only guess with table is that it's trying to record all the different possible outcomes from the ifs here. You get 0 if there's no event, and there's no squirrel. You get 1 if there's an event but no squirrel. You get 2 if there's no event, but there is a squirrel. And you get 3 if there is an event, and a squirrel. You then increment one of four different positions in the table variable based on what transpired.
Since you're iterating over a journal with i, my assumption is that you're trying to keep track of what's happening to you over a long period of time. So if you had, 1 journal entry that added up to 10 and 5 journal entries that added up to 1, and 3 journal entries that added up to 2, then you'd have a table variable with [10, 5, 2, 0] in it.
You can basically think of index as keeping track of all possible states. If there were a third possibility, such as "there is a shark", and it could be independently true or false like the other ones, the index could have a total possible value of 7 (1 + 2 + 4) because the shark one would have to add 4 to index to not step on the toes of the previous two. This is related to the sum of the powers of two SUM (2^n) where n is the number independently possible different things that could happen to you.
for (var i = 0; i < journal.length; i++) {
var entry = journal[i];
var index = 0;
if (hasEvent(event, entry)) {
index += 1;
}
if (entry.squirrel) {
index += 2;
}
table[index] += 1;
}
Generally if you're going to get into programming you need to learn to Google this stuff for yourself. It can be difficult at first, but it is an invaluable skill to learn. I'd rather hire a novice developer that could Google his way out of a problem then an intermediate developer who couldn't reliably find answers on Google.

Categories

Resources