user3477993 user3477993 - 7 months ago 5
Javascript Question

Going on a new line when the array reaches a number higher than x

The issue is as followed: i'm trying to make a piece of code that will print all the elements of an array until it reaches an number higher than 30 lets say. When it does reach that number, the code should start on a new line.
For example, i have the array:

[5, 34, 8, 31, 7, 5, 4, 39, 9, 10, 11, 32, 14];


When the code is finished, it should print something like this:

5, 34
8, 31
7, 5, 4, 39
9, 10, 11, 32
14


All i've been able to do so far is:

var array1 = [5, 34, 8, 31, 7, 5, 4, 39, 9, 10, 11, 32, 14];
for (i = 0; i < array1.length; i++){

}


I have no idea how would i continue from here. I've tried different stuff that came through my mind, but nothing worked. Could someone explain? I'm not here just for the solving, but more for the explanation.

Thank you.

Answer

Assuming you are writing to the console:

var array1 = [5, 34, 8, 31, 7, 5, 4, 39, 9, 10, 11, 32, 14];

var value = '';
for (var i = 0; i < array1.length; i++) {
    var number = array1[i];
    value += value.length > 0 ? ',' + number : number;
    if (number > 30) {
        console.log(value);
        value = '';
     }
}
console.log(value);

this will print to the console this result:

 5,34
 8,31
 7,5,4,39
 9,10,11,32
 14

value is appended to within every iteration of the loop. If the current number is over 30 then value is written to the console. After value is written to the console it is cleared.

Comments