What is Wrong with this Code? I should create a function that receives an array of numbers and returns an array containing only the positive numbers. How can it be modified? Especially Modified. Not another code!

all = prompt("Give me an array of numbers seperated by ','");

var splitted = all.split`,`.map(x=>+x);
function returner(splitted){
    var positive = [];

for(var i = 0; i < splitted.length; i++);{
    var el = splitted[i];
    if (el >= 0){
        positive.push(el);
    }
    
}
return positive;
}

var positive = returner(splitted);
print(positive);
3

There are 3 best solutions below

0
On BEST ANSWER

First I noticed that you are using print to check your output - that should be console.log(). But your real mistake is the semicolon after the for bracket in line 7.

Here is a working code-snippet:

let all = prompt("Give me an array of numbers seperated by ','");

let splitted = all.split`,`.map(x => +x);
function returner(splitted) {
    let positive = [];

    for (let i = 0; i < splitted.length; i++) {
        const el = splitted[i];
        if (el >= 0) {
            positive.push(el);
        }
    }

    return positive;
}

var positive = returner(splitted);
console.log(positive);

1
On

Just remove the semicolon after the for statement as:

all = prompt("Give me an array of numbers seperated by ','");

var splitted = all.split`,`.map(x=>+x);
function returner(splitted){
    var positive = [];

for(var i = 0; i < splitted.length; i++){
    var el = splitted[i];
    if (el >= 0){
        positive.push(el);
    }
    
}
return positive;
}

var positive = returner(splitted);
console.log(positive);

practically with that semicolon you were doing "nothing" n times and then executing the block on it's own which didn't help filling your array since the i variable is already passed the last index of the array and so splitted[i] results to undefined which is not >=0 thus nothing gets pushed to the positive array.

(also I'd imagine you want a console.log at the end instead of print? )

0
On

Why don't you use filter?

var array = [3, -1, 0, 7, -71, 9, 10, -19];

const getpositiveNumbers = (array) => array.filter(value => value > 0);

var positives = getpositiveNumbers(array);

console.log(positives);

Anyway, as @trincot noticed, your code is wrong.