admin管理员组

文章数量:1433500

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

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

Share Improve this question edited Jul 11, 2018 at 11:44 Guillaume Georges 4,0204 gold badges16 silver badges34 bronze badges asked Jul 11, 2018 at 11:34 dilkashdilkash 5924 silver badges15 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 4

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 = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"];
var count = 0;

processedData.some(email => validateEmail(email) && (++count === 2));
 
function validateEmail(email) {
  console.log("validateEmail " + email);
  return (email.indexOf(".") > -1);
}

At least the loop body can be pressed easily:

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

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

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

本文标签: Javascript code refactoring to single line instead of multiple line for loopStack Overflow