This question already has answers here:
Short circuit Array.forEach like calling break
(30 answers)
Closed 3 years ago.
I'm working on a homework problem using JavaScript. I have a solution that currently works, but I am sure that it is not the most efficient way to do it. I am iterating over an array to check if any element meets a certain condition. But there doesn't seem to be a way to exit the forEach() function early. In other languages, I have used break to quit a forEach loop early. Does something similar exist in JavaScript?
My code (simplified for this question):
let conditionMet = false;
numbers.forEach((number) => {
if (number % 3 === 0) {
conditionMet = true;
// break; <-- does not work!
}
});
Rather than using Array.forEach, you can use Array.some (see docs). This function iterates over the elements of the array, checking to see if any element meets a certain condition. If an element is found that meets the condition, the function stops iteration, and returns true. If not, the function returns false. This means that you can also skip the step of initializing conditionMet to false.
Your code can therefore be simplified as:
let conditionMet = numbers.some(number => (number % 3 === 0));
You can’t break .foreach() loop unless through an exception
So you can choose another tool like a simple for loop.
Related
This question already has answers here:
Two semicolons inside a for-loop parentheses
(4 answers)
Empty for loop - for(;;)
(4 answers)
Closed 3 months ago.
It's in JavaScript not C language, so I think it's not duplicate
I was testing some code and I found this one :-
for (;;) {
console.log("test");
}
And the iterations kept going forever
I was wondering what does this ;; mean? And what is its use case?
PS :- don't run it as it will freeze for infinite iteration.
The reason that for(;;) loops forever is because for has three parts, each of which is optional. The first part initializes the loop; the second decides whether or not to continue the loop, and the third does something at the end of each iteration. It is full form, you would typically see something like this:
for(i = 0; i < 10; i++)
If the first (initialization) or last (end-of-iteration) parts are missing, nothing is done in their place. If the middle (test) part is missing, then it acts as though true were there in its place. So for(;;) is the same as for(;true;), which is the same as while(true).
This question already has answers here:
Why can't I use Array#includes for a nested array?
(5 answers)
How to compare arrays in JavaScript?
(61 answers)
Closed 3 months ago.
TL;DR: the JavaScript code below returns false where I'm expecting a true, what's the best workaround?
console.log([['a']].includes(['a']))
I'm pushing arrays into arrays (to work with google sheets ranges in apps script, but the behaviour is the same in regular JavaScript).
I'd like to check if my parent array (let's call it [['a']]) contains specific child array (such as ['a']).
Unfortunately array.includes() doesn't seem to work as expected when the parameter is an array. (the code above returns false when it should be true as far as I know)
Am I missing anything? What do you think would be the best workaround?
The problem is array comparison.
console.log(['a'] == ['a']); //false
As the .includes() method loops through the array on which it is being called, it checks each element to see if it is equal to the value being tested for, until it finds a match, or checks every element of the array. As you can see above, when the value being tested is an array, it will not work.
A work around would be to write your own .includes() function in which you loop through all the child arrays in the parent array, and for each child array, loop through every element, testing whether it is equal to the corresponding element in the test array. You can use the .every() method for this.
let array = [['a']];
function includesArray(parentArray, testArray) {
for (let i = 0; i < parentArray.length; i++) {
if (parentArray[i].every(function(value, index) { return value === testArray[index]})) {
return true;
}
}
return false;
}
console.log(includesArray(array, ['a'])); //true
console.log(includesArray(array, ['b'])); //false
One quick alternative is to compare the JSON strigified arrays instead of comparing arrays directly.
console.log([['a']].map(x => JSON.stringify(x)).includes(JSON.stringify(['a'])))
This question already has answers here:
Short circuit Array.forEach like calling break
(30 answers)
Closed 3 years ago.
I am trying to break from a foreach loop. I want to test conditions and break from the loop once the condition is met. The problem is it keeps looping through the json array, even on the false ones. I just want it to stop if the condition is met. I am aware that you cannot actually break from a foreach loop but what is a good alternative here? I am having trouble understanding where to put the break statements. Thank you very much.
$.ajax({
// Get the values of the cce json file
url: 'file.json',
success: function (data) {
data.forEach(function(row) {
if (row.ATTR == feature.properties.AATR) {
// code to execute here
// once the condition is met once, stop execution of foreach
} else {
// some other code to execute
// keep going
}
You can't break forEach loop. You need to use a different type of loop.
See the docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
You should use a for loop. It is a function that simulate it.
for (var i in data) {
if (condition_to_break) {
break;
}
}
.forEach is a function and doesn't do break.
This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 5 years ago.
This one is probably fairly straightforward, but I haven't succeeded in finding an answer as of yet. Anyway, what I want to do is compare one value against a group of others, and run the script if it matches one of them. Here's the verbose version of I want to do, which works fine, but I'm assuming there's a smarter, less verbose way to achieve this?
function updatePosition(e) {
if((e.target.innerHTML == 1) || (e.target.innerHTML == 4) ||
(e.target.innerHTML == 7)) {
console.log(e.target.innerHTML)
}
}
You can store all the valid comparison inside an array. Then you can use Array#Find() to get a matching value. If there is no matching value, you will get undefined
function updatePosition(num) {
let validNumbers = [1,4,7];
console.log(validNumbers.find(valid => valid === num));
}
updatePosition(4);
updatePosition(9);
This question already has answers here:
Unknown JavaScript syntax before for...in
(3 answers)
Closed 7 years ago.
While reading code from some project, I stumbled on this KEYVAL:
KEYVAL:
for(key_name in arg_map) { // iterates over hash key|value pairs
// if this key_name belongs to this object, not proto
if(arg_map.hasOwnProperty(key_name)) {
// skip dependent keys during iteration
if(key_name.indexOf('_') === 0) { continue KEYVAL; }
// update independent key value
anchor_map_revise[key_name] = arg_map[key_name];
// update matching dependent key
key_name_dep = '_' + key_name;
if(arg_map[key_name_dep]) {
anchor_map_revise[key_name_dep] = arg_map[key_name_dep];
} else {
delete anchor_map_revise[key_name_dep];
delete anchor_map_revise['_s' + key_name_dep];
}
} // if end
} // for end
What is that? What the purpose of this? Is it part of JS syntax?
It is a label. A label is an identifier (here: KEYVAL), followed by a colon (:), that precedes a statement (in this case, for).
A continue or break statement can use a label (in your case continue KEYVAL) to specify which loop to continue with, or break from. In this case, the KEYVAL: for is the innermost loop, so the label is actually not necessary; but labels are useful if you need to break from several levels at once.
See more on MDN.
EDIT: for, not while.