i’m totally new to coding: i want to iterate through the array input, select the positive numbers only, then put them in a new array liste and then print the new array in the console. what am i doing wrong here?!?
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];
var liste = [];
function cut(input){
for (var i=0; i<cut.length; i++){
if (i>0){
liste.push(input[i]);
return liste;
}
}
var result = cut(input);
console.log(result);
>Solution :
Since I can’t accurately portray in a comment what I would want to explain, I am posting an answer:
I find it much easier to balance braces when I format my code like so
function cut(input)
{
for (var i=0; i<cut.length; i++)
{
if (i>0)
{
liste.push(input[i]);
return liste;
}
}
And now its pretty apparent where the unbalanced brace is.
There are other syntax errors that others have already been pointed out:
- Its not
cut.length, ratherinput.length. - Your
ifstatement needs to beif (input[i] > 0), notif (i > 0) return listeshouldn’t be inside of the loop, rather at the end of the function, because once a value is found it will stop the loop and immediately return only 1 value inside of the array.
Here should be a working example of what you intended to do. Other than those few syntax errors, good job with the logic!
let input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];
function cut(input){
let liste = [];
for (var i=0; i<input.length; i++){
if (input[i]>0){
liste.push(input[i]);
}
}
return liste;
}
var result = cut(input);
console.log(result);