0

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);
  • 2
    I vote to close this as a typo: you have a semi colon at the end of the `for` line, which means the code block that follows it, is not the body of the `for` loop. That block will have `i` equal to the length of the array... – trincot Feb 28 '21 at 20:47
  • Does this code actually run? If it does, what input are you providing, what result are you seeing, and what result were you expecting? – jarmod Feb 28 '21 at 20:48
  • Also use `console.log` instead of `print`. `print` will launch the printer dialog :) – Paul Rooney Feb 28 '21 at 20:49

3 Answers3

1

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);
kritzl
  • 26
  • 2
0

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? )

Dario Piotrowicz
  • 951
  • 1
  • 6
  • 14
0

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.

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21