1

I want to loop through an array of numbers to see if it matches up with a variable that i want to check for. It's doing the check correctly but it's displaying the result every time it checks it. What i want it to do is....do the check and just spit out the result only once its finished. Is there a way to do that?

            var myNumber = 123;
            var sponsorNumber = [345, 234, 525];

            angular.forEach(sponsorNumber, function(value) {
              if (value !== myNumber) {              
                console.log('doesnt match!');
              }
            });

3 Answers 3

3

Do not print the message inside the loop. You need to maintain a flag that weather it found or not. And then print in the end.

However you don't need foreach here. Just try indexOf function.

 if (sponsorNumber.indexOf(myNumber) < 0 ) {              
       console.log('doesnt match!');
   }
Sign up to request clarification or add additional context in comments.

Comments

0

Why don't you use simple Array.prototype.indexOf() to do what you actually want? If it returns -1, then you know the array doesn't contain you number. There's no need to reinvent the wheel if there's already a perfect one.

Comments

0

If that's what you want, you can filter and then loop (less efficient):

sponsorNumber.filter(value => value !== myNumber).forEach(function(value) {
    console.log('doesnt match!');
});

But it does not make too much sense to me. I think you want something else, like the others commented, using indexOf.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.