So I am trying to create a function where it will display to me the FIRST even number divisible by 2. The values to be divided are inside an array and another function helps me determine whether the values in the array are divisible by 2. The problem is that the loop won't break and the loop continues until the last value of the array. I want it to break once it finds the first number divisible by 2. So in this case the loop should stop once it reaches value 8 in the array but it doesn't and continues until 10. I hope you can help me
This is my code:
function findElement(arr, func) {
var num = 0;
arr.sort();
for(var i = arr[0]; i <= arr[arr.length-1]; i++) {
if(func(arr[i])) {
num = arr[i];
break;
}
if(!func(arr[i])) {
num = undefined;
}
}
return num;
}
findElement([1, 3, 5, 8, 9, 10], function(num){ return num % 2 === 0; });
I believe your for over array is off.
Instead of
for(var i = arr[0]; i <= arr[arr.length-1]; i++) {
It should be
for(var i = 0; i <= arr.length-1; i++) {
Otherwise, you might as well be verifying undefined array indexes.
Please remove arr.sort() your function works find
please find the updated code .its working fine run and check.
function findElement(arr, func) {
var num = 0;
// arr.sort();
for(var i = arr[0]; i <= arr[arr.length-1]; i++) {
if(func(arr[i])) {
num = arr[i];
break;
}
if(!func(arr[i])) {
num = undefined;
}
}
return num;
}
console.log(findElement([1, 3, 5, 8, 9, 10], function(num){ return num % 2 === 0; }));
I need some help. I have 2 loops to traverse two lists of records . The thing is that at some point should put a break or something, because the last loop crushes the value I'm looking for.
This is my code
for (var i in $scope.users) {
for (var j in $scope.states) {
if ($scope.users[i].id === $scope.states[j].user) {
if ($scope.states[j].estado === 'totallyBussy') {
$scope.users[i].estado= 'Not available';
} else if ($scope.states[j].estado === 'partlyBussy') {
$scope.users[i].estado= 'Maybe available';
}
}
else {
$scope.users[i].estado= 'Available';
}
}
}
Where user 4 and user 5 should be 'Maybe available' and 'Not available', but with this code, I'm getting 'Available for user 0, 1, 2, 3, and the last one. And the last one is crushes with else.
I hope I explained well.
Thanks so much
You can use the break keyword, which will end the loop when executed.
One side note: you don't want to use for (var i in array) {} since you may iterate through Array properties (and have i take unexpected values).
I updated your code with a more reliable iteration.
for (var i = 0, il = $scope.users.length; i < il; i++) {
var user = $scope.users[i];
for (var j = 0, jl = $scope.states.length; j < jl; j ++) {
var state = $scope.states[j];
if (user.id === state.user) {
if (state.estado === 'totallyBussy') {
user.estado = 'Not available';
} else if (state.estado === 'partlyBussy') {
user.estado = 'Maybe available';
}
// Go to the next user (break the "states" loop)
break;
} else {
user.estado = 'Available';
}
}
}
EDIT: If $scope.users and $scope.states are not Arrays but actually Objects (which would seem strange to me but anyway), you can keep for (var i in object) {} but you have to add a check: if (object.hasOwnProperty(i)) {} in the loop.
you can add a flag which will become true when you got your desired value.
something like
var gotValue = false;
for (var i in $scope.users) {
if(!gotValue)
{
for (var j in $scope.states) {
if ($scope.users[i].id === $scope.states[j].user) {
if ($scope.states[j].estado === 'totallyBussy') {
$scope.users[i].estado= 'Not available';
gotValue = true;
} else if ($scope.states[j].estado === 'partlyBussy') {
$scope.users[i].estado= 'Maybe available';
gotValue = true;
}
}
else {
$scope.users[i].estado= 'Available';
gotValue = true;
}
}
}
}
In AngularJS, there is no break for loops,etc., so one has to go with logic manually.
A similar case has been demonstrated here.
Here, I have created a variable f, which has been set to false initially. On forEach loop, based on a condition, it is made to true, further which it works as break.
Please find the code below:
HTML:
<div ng-app="app" ng-controller="test"></div>
JS:
var app = angular.module('app',[]);
app.controller ('test', function ($scope){
var f = false;
angular.forEach([1,2,3,4,5], function(v,k){
if(k > 2){
f = true;
}
if(!f) {
document.write('value = ' + v + ' <br>');
}
});
});
I have an angular foreach loop and i want to break from loop if i match a value. The following code does not work.
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
How can i get this?
The angular.forEach loop can't break on a condition match.
My personal advice is to use a NATIVE FOR loop instead of angular.forEach.
The NATIVE FOR loop is around 90% faster then other for loops.
USE FOR loop IN ANGULAR:
var numbers = [0, 1, 2, 3, 4, 5];
for (var i = 0, len = numbers.length; i < len; i++) {
if (numbers[i] === 1) {
console.log('Loop is going to break.');
break;
}
console.log('Loop will continue.');
}
There's no way to do this. See https://github.com/angular/angular.js/issues/263. Depending on what you're doing you can use a boolean to just not going into the body of the loop. Something like:
var keepGoing = true;
angular.forEach([0,1,2], function(count){
if(keepGoing) {
if(count == 1){
keepGoing = false;
}
}
});
please use some or every instances of ForEach,
Array.prototype.some:
some is much the same as forEach but it break when the callback returns true
Array.prototype.every:
every is almost identical to some except it's expecting false to break the loop.
Example for some:
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
ary.some(function (value, index, _ary) {
console.log(index + ": " + value);
return value === "JavaScript";
});
Example for every:
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
ary.every(function(value, index, _ary) {
console.log(index + ": " + value);
return value.indexOf("Script") > -1;
});
Find more information
http://www.jsnoob.com/2013/11/26/how-to-break-the-foreach/
Use the Array Some Method
var exists = [0,1,2].some(function(count){
return count == 1
});
exists will return true, and you can use this as a variable in your function
if(exists){
console.log('this is true!')
}
Array Some Method - Javascript
As far as I know, Angular doesn't provide such a function. You may want to use underscore's find() function for this (it's basically a forEach which breaks out of the loop once the function returns true).
http://underscorejs.org/#find
If you use jQuery (hence not jqLite) in conjunction with AngularJS you can iterate with $.each - which allows breaking and continuing based on boolean return value expression.
JSFiddle:
http://jsfiddle.net/JEcD2/1/
Javascript:
var array = ['foo', 'bar', 'yay'];
$.each(array, function(index, element){
if (element === 'foo') {
return true; // continue
}
console.log(this);
if (element === 'bar') {
return false; // break
}
});
Note:
Though using jQuery is not bad, both native Array.some or Array.every functions are recommended by MDN as you can read at native forEach documentation:
"There is no way to stop or break a forEach loop. The solution is to use Array.every or Array.some"
Following examples are provided by MDN:
Array.some:
function isBigEnough(element, index, array){
return (element >= 10);
}
var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true
Array.every:
function isBigEnough(element, index, array){
return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true
Concretely, you can exit of a forEach loop, and of any place, throw an exception.
try {
angular.forEach([1,2,3], function(num) {
if (num === 2) throw Error();
});
} catch(e) {
// anything
}
However, it is better if you use other library or implement your own function, a find function in this case, so your code is most high-level.
Try this as break;
angular.forEach([0,1,2], function(count){
if(count == 1){
return true;
}
});
As the other answers state, Angular doesn't provide this functionality. jQuery does however, and if you have loaded jQuery as well as Angular, you can use
jQuery.each ( array, function ( index, value) {
if(condition) return false; // this will cause a break in the iteration
})
See http://api.jquery.com/jquery.each/
Normally there is no way to break an "each" loop in javascript.
What can be done usually is to use "short circuit" method.
array.forEach(function(item) {
// if the condition is not met, move on to the next round of iteration.
if (!condition) return;
// if the condition is met, do your logic here
console.log('do stuff.')
}
break isn't possible to achieve in angular forEach, we need to modify forEach to do that.
$scope.myuser = [{name: "Ravi"}, {name: "Bhushan"}, {name: "Thakur"}];
angular.forEach($scope.myuser, function(name){
if(name == "Bhushan") {
alert(name);
return forEach.break();
//break() is a function that returns an immutable object,e.g. an empty string
}
});
You can use this:
var count = 0;
var arr = [0,1,2];
for(var i in arr){
if(count == 1) break;
//console.log(arr[i]);
}
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
var keepGoing = true;
ary.forEach(function(value, index, _ary) {
console.log(index)
keepGoing = true;
ary.forEach(function(value, index, _ary) {
if(keepGoing){
if(index==2){
keepGoing=false;
}
else{
console.log(value)
}
}
});
});
$scope.arr = [0, 1, 2];
$scope.dict = {}
for ( var i=0; i < $scope.arr.length; i++ ) {
if ( $scope.arr[i] == 1 ) {
$scope.exists = 'yes, 1 exists';
break;
}
}
if ( $scope.exists ) {
angular.forEach ( $scope.arr, function ( value, index ) {
$scope.dict[index] = value;
});
}
I would prefer to do this by return. Put the looping part in private function and return when you want to break the loop.
I realise this is old, but an array filter may do what you need:
var arr = [0, 1, 2].filter(function (count) {
return count < 1;
});
You can then run arr.forEach and other array functions.
I realise that if you intend to cut down on loop operations altogether, this will probably not do what you want. For that you best use while.
This example works. Try it.
var array = [0,1,2];
for( var i = 0, ii = array.length; i < ii; i++){
if(i === 1){
break;
}
}
I would use return instead of break.
angular.forEach([0,1,2], function(count){
if(count == 1){
return;
}
});
Works like a charm.
Use Return to break the loop.
angular.forEach([0,1,2], function(count){
if(count == 1) {
return;
}
});
onSelectionChanged(event) {
let selectdata = event['api']['immutableService']['gridOptionsWrapper']['gridOptions']['rowData'];
let selected_flag = 0;
selectdata.forEach(data => {
if (data.selected == true) {
selected_flag = 1;
}
});
if (selected_flag == 1) {
this.showForms = true;
} else {
this.showForms = false;
}
}
Just add $index and do the following:
angular.forEach([0,1,2], function(count, $index) {
if($index !== 1) {
// do stuff
}
}