3

What is the most efficient way to check a certain condition on every element of an array and return false if one or more elements do not meet the condition, for example, I have this array for example

arr = ["foo","azeaze", "wazeazerar"]
    for(var ar in arr){
      if(ar.length > 5){
        console.log(false)
      }else{
        console.log(true)
      } 
    }

as you can see it return true even if the element "foo" length is not greater than 5

Yogi
  • 609
  • 1
  • 8
  • 21
arkahn jihu
  • 109
  • 4

1 Answers1

8

You can use Array.prototype.every() in a one line function

arr = ["foo","azeaze", "wazeazerar"]

const isittrue = currentval =>  currentval.length > 2

console.log(arr.every(isittrue));

 arr = ["foo","azeaze", "wazeazerar"]
    console.log(arr.every(elem => elem.length >= 5))
Abslen Char
  • 3,071
  • 3
  • 15
  • 29
  • Thank you sir , thankfully you did answear my question before the admin mark it as duplicated because i didnt understund why he mark it as duplicated even if it wasnt what I was asking – arkahn jihu Apr 08 '18 at 08:43