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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With