简体   繁体   中英

Javascript: code refactoring to single line instead of multiple line for loop

I am new to react and javascript , trying to refactor my below code to fewer lines:

for (const email of processedData) {
     if (validateEmail(email)) {
          count++;
          if (count === 100) {
             break;
           }
      }
 }

processedData is a list of emails, tried using reduce but in reduce i could not break once i have count === 100

Thanks

At least the loop body can be compressed easily:

for(const email of processedData) {
    if(validateEmail(email) && ++count === 100) break
}

It would be hard to make it even shorter. >_>

Array.prototype.some will run a function on your array's element until that function returns true.

Then you can do something like this :

EDIT : single line version of my first suggestion.

 var processedData = ["joe@test.co.uk", "john@test.co.uk", "jack@test.com", "jane@test.com", "amy@test.com"]; var count = 0; processedData.some(email => validateEmail(email) && (++count === 2)); function validateEmail(email) { console.log("validateEmail " + email); return (email.indexOf(".com") > -1); } 

Well, if you just want to have an array with 100 items, then this could help. Apply .filter() on the data array and then slice it to 100.

processedData.filter(email => validateEmail(email)).slice(0,100)

I think... it shoud help, but probably is better way to refactor (as always)

for(const email of processedData){
  if(validateEmail(email) && count != 100) count++
}

How about using below loop?

for(let i=0,count=0; i < processedData.length && count<100; i++){
    count+=validateEmail(processedData[i])
}

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