Search code examples
javascriptarraysmap-function

map function to return 1 boolean value, instead of an array of boolean values


Say you have an array like this:

arrayExample = [1, 2, 3, 4, 5, 6, 7]

I want to use the map function to iterate through arrayExample and return true if all the numbers are less than 8, false if they are not. However, when I do this I get an array of trues (like: [true, true, true... etc])

Would I be able to return just 1 value?

Here is my code so far:

var testBoolean = true;
var array = [1,2,3,4,5,6,7];

testBoolean = array.map(m => { 
    //if a number in the array is >=8, changes the testBoolean to false and return false only
    if(m >= 8) 
    { 
        return false;
    }
    //VS code said I had to have a return here, I believe its because I need to have in case m < 8 (edited after reading a comment)
    return true;
 })
 
 //prints an array [true,true,true,true,true,true,true]
document.write(testBoolean); 

I'm a bit new to "map" but I believe it does this since it returns a value for every element, just confused on how to make it so it returns 1 true or false.


Solution

  • For something like this .map() isn't the right tool. .map() is for converting all the elements in your array to new elements (ie: mapping each element to a new transformed value). As a result, .map() will always return an array (unless this behaviour is intentionally modified). Instead, you can use .every() for this, which will tell you if all elements in your array match your condition (ie: if your function returns true for every element, then you'll get true as your result, otherwise you'll get false). The .every() method will terminate early as soon as it finds one element which your callback function returns false for, which can help with efficiency:

    const array = [1, 2, 3, 4, 5, 6, 7];
    const testBoolean = array.every(m => {
      if (m >= 8) {
        return false;
      }
      return true;
    });
    console.log(testBoolean);

    This can be written more concisely, by just returning the result of m < 8 (this will either evaluate to true or false)

    const array = [1,2,3,4,5,6,7];
    const testBoolean = array.every(m => m < 8);
    console.log(testBoolean);