Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

iterate through array in javascript and return in new array

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  1. Its not cut.length, rather input.length.
  2. Your if statement needs to be if (input[i] > 0), not if (i > 0)
  3. return liste shouldn’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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading