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

3
  • Have you tried debugging this on your own to see what ar contains? Commented Apr 8, 2018 at 8:28
  • It marked as duplicated even if it dosent answear my question Commented Apr 8, 2018 at 8:42
  • Sure, it does: you should not use for... in if you want to iterate over the values of an array Commented Apr 8, 2018 at 9:23

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.