How to stop the cycle after it is detected?

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

I use filter() - is this the 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

+6
source share
4 answers

In this context, you can use array#some ,

 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 true value returned inside the callBack function. Therefore, if any matches found a value, if the function returned with the value true , then the element at this particular iteration will be assembled into an array , and finally, the array will be returned.

Therefore, in your case, ["three", "theree"] will be returned as a result. If you do not have "three" then an empty array will be returned. In this context, you need to do an additional check to find the true value in it.

Example:

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

So, to avoid this situation, we use Array # some.

+6
source

 var data = [ 'one', 'two', 'three', 'four', 'three', 'five', ]; for(var i=0;i<data.length;i++){ console.log(data[i]); if(data[i]=="three"){ var found=data[i]; break; } } console.log(found); 
0
source

You must return false to exit the function, but you are already using the return statement in the filter function, and you cannot use 2 return statements ... Another solution I came up with:

 var data = [ 'one', 'two', 'three', 'four', 'three', 'five', ]; var filteredData = []; function a(i,e){ console.log(e); if(e == "three"){ filteredData.push(e); return false; } } $(data).each(a); console.log(filteredData); 

This will happen as soon as it falls into the “three” and also save it in the filtersData array so you can use it in the future ... I hope this helps ...

0
source

A simple approach.

  var data = [ 'one', 'two', 'three', 'four', 'three', 'five', ]; found = data.indexOf('three') == -1 ? false : true; console.log(found); 
0
source

Source: https://habr.com/ru/post/1013504/


All Articles