Why doesn't console.log() concatenate strings? - javascript

In this example I try to print one asterisk on the first line, two on the second and so on:
var n = 5;
for (i = 0; i < n; i++) {
for (j = 0; j < i; j++) {
console.log('*');
}
console.log('\r\n');
}
The output should look like this:
*
**
***
****
*****
But in the Chrome console I see this:
*
2 *
3 *
4 *
5 *
Why is this?

console.log is not designed to precisely control the rendering of the output. It is a log writer, not a terminal layout API.
It puts each log message on a line of its own, and collapses duplicate, sequential log messages into a single message with a count of the number of times it occurred next to it.

It's doing that because it's how dev tools handles multiple occurrences of the same value for the purposes of clarity.
You can use an array to achieve the effect you're after. Also note that we change j<i to j<= so that it outputs on the 5th.
Then, we use the .join('') method to flatten the array into a string.
Also, since we are console.logging on every iteration loop, a new line will be added automatically as it's one log per loop.
var n = 5;
for (i = 0; i < n; i++) {
var arr = [];
for (j = 0; j <= i; j++) {
arr.push('*');
}
console.log(arr.join(''));
}
Please note that you wouldn't need an array if you were printing this into the DOM - it would work as you originally intended it to do.
Update: Ivar made a great solution as well and that's to use the String.repeat() function which only requires you to use one loop.
var n = 5;
for (i = 1; i <= n; i++) {
var str = '*';
str = str.repeat(i);
console.log(str);
}

Because that's the way it works, basically. Each call to console.log outputs a new log entry. Each log entry is in its own line.
If you log the same string multiple times, they will get summarized into one entry with the count in front.
Don't mistake console.log with Console.Write in C# or similar. It's more like Console.WriteLine.

Related

Infinite Loop for finding a power set for a string

I'm working on a problem where I need to find all the power set of a given string which are all the possible subsets. I feel like I'm close with my current code but I can't figure out why I'm getting stuck on an infinite loop for my second iteration. I ran it through the debugger but I still can't seem to figure it out even though I'm sure it's very simple. When i = 0 then it goes to the second loop where j = 0 && j < 1 so for example if help is my given str argument then I would expect it to add j + '' and push it into my allSubsets array. The problem is that the j iteration will keep looping and doing j++ and will never stop. I'm not sure why this is. One particular question even if I solve this infinite loop - do I need to update the allSubsets.length in the iteration to keep it updated with the pushed in strings?
var powerSet = function(str) {
let allSubsets = [''];
for (let i = 0; i < str.length; i++) {
debugger;
for (let j = 0; j < allSubsets.length; j++) {
allSubsets.push(sortLetters(str[i] + allSubsets[j]));
}
}
return allSubsets;
};
var sortLetters = (word => {
//convert string to an array
//use the sort to sort by letter
//convert array back to string and return
return word.split('').sort().join('');
})
Everytime you push to allSubSets, the length increases, and thus, your loop never ends. A declarative loop runs on the range of the initial loop. See below for a fix based on your code:
var powerSet = function(str) {
let allSubsets = [''];
for (let i = 0; i < str.length; i++) {
allSubsets.forEach( (_char, j) => { // declarative loop here
allSubsets.push(sortLetters(str[i] + allSubsets[j]));
})
}
return allSubsets;
};
var sortLetters = (word => {
return word.split('').sort().join('');
})
From MDN web docs:
The range of elements processed by forEach() is set before the first invocation of callback. Elements which are appended to the array after the call to forEach() begins will not be visited by callback. If existing elements of the array are changed or deleted, their value as passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using shift()) during the iteration, later elements will be skipped. (See this example, below.)
See the fourth paragraph under descriptions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description

Possible bug/misunderstanding of splice and slice

I have the next loop:
rolling_average_delta_follower=[];
followers=[32,34,36,38,40,42,44,46,48,50,52,54,56] // .length = 12
delta_followers=[50,52,54,56,58,60,62,64,66,68,70,72,74] // leng= 12
for (i = 0; i < followers.length ; i++) {
copie = delta_followers.slice(0); //creates duplicate of array delta_followers so I keep source original and not cut from it
copie.splice(7,i) // supposed to create an array that contains numbers from 50 to 64 -> next time the for executes it should go 52 to 66 and so on
console.log(copie)
for (i = 0; i < 8; i++) { // the 7 numbers added previously in the one array are getting summed up
totalx += copie[i]
}
rolling_average_delta_follower.push(totalx) // the sum of each array previously created is getting added to the main array where I need the data.
}
All good until I try to actually execute it, I end up with with a forever loop that I seem not to be able to escape.
Any help would be appreciated.
Thank you!
The problem is here:
for (i = 0; i < 8; i++) { // the 7 numbers added previously in the one array are getting summed up
totalx += copie[i]
}
By this code you override i used in the loop above.
Just use another variable name here. (j ?)
To make a copy of an array use the spread operator.
const copy = [...original];
To sum the values of an array use reduce.
const sum = array.reduce((sum, item) => sum + item, 0);

Apps Script JS adding items to array from range (if not already in array) fails

I am looping through various cells and want to add their string content do an array, if the content is not already in the array. It works perfectly fine when I do it manually like so, trying to add 'eJobs' to the array (see below "var item = 'eJobs') which already containts 'eJobs':
var divisionarray = ['eJobs']
for (var i = 0; i < cells_users.length-1; ++i) {
var row_users = cells_users[i];
if (row_users[0] == user_ldap) {
var podarray = row_users[1].split(', ')
for (j = 0; j < podarray.length; j++) {
for (var k = 0; k < cells_edit.length; ++k) {
var row_edit = cells_edit[k]
if (podarray[j] === row_edit[0]) {
var item = 'eJobs'
if (!(divisionarray.indexOf(item) >= 0)) {
divisionarray.push(item)
}
}
}
}
Logger.log(divisionarray)
As expected, the log file shows [17-10-08 19:11:04:111 BST] [eJobs], illustrating that the code works and 'eJobs' has not been added to the array as it is already in the array.
Now, when I change var item='eJobs' to values of a range
var item = sheet_pods_edit.getRange(startRow+k, startColumn+1).getValue();
the code does not work anylonger, as the log file shows:
[17-10-08 19:14:03:770 BST] [eJobs, eJobs, BestJobs, Vivre Deco, ...
Note I have a range of thousands of cells, so I get alot of duplicates added. What am I missing? Note the cells of the defined range are indeed just strings with a single word (e.g. 'eJobs').
The code is working and the log file is indicating what the problem is..
[eJobs, eJobs, BestJobs, Vivre Deco,
In the second eJobs there is a white space before eJobs, so the first value and the second value don't match.
Without seeing your data and going by the 'just strings with a single word' I would say that using a .replace(" ", "") on the text string should work, this will find the first " " in the string and remove it. I.e. " eJobs" would become "eJobs".
2.
Is this line of code just for testing? You should never use a method like this in a script. It will be extremely inefficient
var item = sheet_pods_edit.getRange(startRow+k, startColumn+1).getValue();
Instead get the full range using .getValues()and iterate over it then.
3.
Is there a reason you are using === in if (podarray[j] === row_edit[0]) unless you need to check for type always use ==

How to Loop Through ths Array in JavaScript

I'm new to Javascript and I am begining to learn.
I need help understanding; how can I retrieve each carachter of this array.
var possibleRaysPasswords =['mobleyAndTrentonAreDead','tyrellIsElliot','dreadPirateRoberts'];
Like in these example:
e.g: femtocell
f
fe
fem
femt
femto
femtoc
femtoce
femtocel
femtocell
Much appreciated.
If you want to get each character of each element, you may do a simple array transformation to get you an array of all the characters in all the items:
var allOfThem = arr.join('').split('');
That is: you first join all the elements into a single string. and then you split this string into array of characters. Then you can loop over it.
Can you provide an example of what you've tried so far? Doing so will help us to answer any confusion you have.
For a start, let's demonstrate how to loop through each element in the array. We can declare an array the way you demonstrated:
var myArray = ["elements", "are", "pretty", "cool! "];
To loop through this array, we can simply use a for loop.
for (var i = 0; i < myArray.length; ++i) {
console.log(myArray[i]); // this provides the element at the ith index of the array
}
This will log, in order:
elements
are
pretty
cool!
You can access the individual characters of a string in the same exact way that you access individual elements of an array. Try that and see if you can get to where you need to be.
You could use two nested loop, one for the array and one for the atrings for the letters in combination with String#slice
var possibleRaysPasswords =['mobleyAndTrentonAreDead','tyrellIsElliot','dreadPirateRoberts'],
i, j;
for (i = 0; i < possibleRaysPasswords.length; i++) {
for (j = 1; j <= possibleRaysPasswords[i].length; j++) {
console.log(possibleRaysPasswords[i].slice(0, j));
}
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Let me know if something is unclear. The comments in the code should tell you what's going on though:
// making this a constant, because we only want to read from this data
const passwords = ['mobleyAndTrentonAreDead', 'tyrellIsElliot', 'dreadPirateRoberts'];
// somewhat recently, we can also define functions like this
const printPassword = password => {
// this function prints out the password starting from the first character, all the way to its end
// if the password is 'test', the output should be 't te tes test'
let resultString = ''; // this will be returned later
// let's use the good old for loop
// start at the first character (zero-indexed), and use the counter variable i to mark the end of the substring
for (let i=1; i <= password.length; i++) {
resultString += password.substring(0, i) + ' ';
}
return resultString;
};
// iterating over every password in the passwords array,
// and log the returned string to the console
passwords.forEach(password => console.log(printPassword(password)));
user 'forEach' to iterate elements of array and 'substr' to part of string:
var possibleRaysPasswords =['mobleyAndTrentonAreDead','tyrellIsElliot','dreadPirateRoberts'];
possibleRaysPasswords.forEach(function(element){
for(var i=0 ; i<element.length ; i++){
console.log(element.substr(0,i));
}
});
'for of' can also be used for iteration:
for (element of possibleRaysPasswords){
for(var i=0 ; i<element.length ; i++){
console.log(element.substr(0,i));
}
}
As simple as that:
var letters = [];
for(let i of possibleRaysPasswords ){letters.push.apply(letters,i.split(""))}
console.log(letters);
That will create and array with all letters. Not sure if that was the question though

Why doesen't prompt() inside a for loop in javascript work for my code below?

Why doesen't prompt() inside a for loop in javascript work for my code below?
var P = [];
for(i=0;i++;i<10)
{
var g=parseInt(prompt("What is the money you paid in"+i+ "month?"));
P[i]=g;
}
Your for loop is wrong. It should be
for (i=0;i<10;i++)
You mixed up the second and third parts. The condition comes second, the variable increment comes last.
You swapped the parts of the for loop. The condition is second:
for(var i = 0; i < 10; i++) {
Also don't forget var, and parseInt(x, 10) prevents some weird behaviour.
Your loop is formatted incorrectly, a for loop should be:
for ( state; condition; action )
So, given your case, the correct loop is:
for (var i = 0; i < 10; i++)

Categories