简体   繁体   中英

How to return multiple results into an array?

The task is to build a function where it receives an array and a number that will work as a limit. The thing is that it should return an array with the resulting booleans like this:(ie [true, false, false]). But I can't figure out how.

I tried using a for loop to stuff an empty array, but it returns just false.

function aperturas(arrayDeIngresosSemanales, cantMinEst) {

    for (var i = 0; i < arrayDeIngresosSemanales.length; i++) {

    var a = 0;
    var arr = arrayDeIngresosSemanales[i];

    for (var j = 0; j < arr.length; j++) {



    if (arr[j] <= 0) {
        a = a + 1;
      }

    }
    if (a >= cantMinEst) {

      return true;
    } else {

      return false;
    }
  }

}

aperturas([0, 0, 3, 0], [1, 2, 4, 5], [0, 0, -1], 3);

return breaks out of the function - have a result array instead:

function aperturas(arrayDeIngresosSemanales, cantMinEst) {
  let result = [];

  // ...

  if (a >= cantMinEst) {
    result.push(true);
  }
    result.push(false);
  }

  // ...      

  return result;

}

You could even remove the if statement:

result.push(a >= cantMinEst);

Or, alternatively if you want to use a more semantic JS feature than the for loop, you could keep the return statements but use the map function instead. That would look something like this:

arrayDeIngresosSemanales.map((arr) => {
    var a = 0;

    for (var j = 0; j < arr.length; j++) {
        if (arr[j] <= 0) {
            a = a + 1;
        }
    }
    if (a >= cantMinEst) {
        return true;
    } else {
        return false;
    }
})

By that same token, you could also replace the inner for loop with a reduce , but that will be left as an exercise for the reader.

You shouldn't return immediately after evaluating an array element.

Create a result array and push result of each array's evaluation and return the result.

Also, you aren't calling the function properly. First argument is an array of arrays, you have to call it like aperturas([[0, 0, 3, 0], [1, 2, 4, 5], [0, 0, -1]], 3)

 function aperturas(arrayDeIngresosSemanales, cantMinEst) { // Create an array to store the result. var result = []; for (var i = 0; i < arrayDeIngresosSemanales.length; i++) { var a = 0; var arr = arrayDeIngresosSemanales[i]; for (var j = 0; j < arr.length; j++) { if (arr[j] <= 0) { a = a + 1; } } // Now compare with limit after iterating completely over the array. if (a >= cantMinEst) { result.push(true); } else { result.push(false); } } // After iterating over all the arrays, return the result. return result; } console.log(aperturas([[0, 0, 3, 0], [1, 2, 4, 5], [0, 0, -1]], 3)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM