0

How to get element with specific length (ex: length = 7) in array If there's no element with length = 7, I want to print something. If I do inside the loop it will print many times base on number of element.

let txt = `abc klj 1123 MPM SN67990 MKP LJJ`
let arr = txt.split(' ')
console.log(arr)

for (let i = 0; i < arr.length; i++) {

    if (arr[i].length == 7) {
        console.log(arr[i])
    } 
    
    // TODO: if no element with length = 7 in arr
}

Athirah
  • 13
  • 3
  • [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+check+if+array+has+no+element+satisfies+condition) of [Check if all elements satisfy a condition with for-loop](/q/49653831/4642212). – Sebastian Simon Aug 19 '21 at 01:13
  • So add a variable and check outside `var hasItem = false; for(...) { if(length 7) { hasItem=true;}} if(!hasItem) { alert('nope'); }` – epascarello Aug 19 '21 at 01:16

1 Answers1

2

Check that .every one of the elements passes the length test.

if (arr.every(subarr => subarr.length !== 7)) {
  // then no array with length 7 exists
}

Another method - use a regular expression to match 7 characters, no array required.

if (!txt.match(/\b\S{7}\b/)) {
  // then no word exactly 7 characters long exists
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320