Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop looping once it found?

Tags:

javascript

If three is found then it should return true and stop the iteration. Otherwise return return false if not found.

I am using filter() - is it wrong approach to use?

var data = [
  'one',
  'two',
  'three',
  'four',
  'three',
  'five',
];

found = data.filter(function(x) {
   console.log(x);
   return x == "three";
});

console.log(found);

Demo: https://jsbin.com/dimolimayi/edit?js,console

like image 611
I'll-Be-Back Avatar asked Dec 25 '16 14:12

I'll-Be-Back


People also ask

How do you stop a loop once a value is found?

The purpose the break statement is to break out of a loop early. For example if the following code asks a use input a integer number x. If x is divisible by 5, the break statement is executed and this causes the exit from the loop.

How do you stop a loop when a condition is met in Python?

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.

How do you end a loop in Python?

The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.


1 Answers

You can use array#some at this context,

var data = [
  'one',
  'two',
  'three',
  'four',
  'three',
  'five',
];

found = data.some(function(x) {
   return x == "three";
});

console.log(found); // true or false

If you use filter, then the array will be filtered based on the truthy value returned inside of the callBack function. So if any matches found meaning, if the function returned with value true, then the element on that particular iteration will be collected in an array and finally the array will be returned.

Hence in your case ["three", "theree"] will be returned as a result. If you dont have any "three", then an empty array would be returned, At this context you have to make a additional check to find the truthy value as a result.

For Example:

var res = arr.filter(itm => someCondition);
var res = !!res.length;
console.log(res); //true or false.

So to avoid that over killing situation we are using Array#some.

like image 180
Rajaprabhu Aravindasamy Avatar answered Oct 02 '22 04:10

Rajaprabhu Aravindasamy