How does one break out of a forEach loop? [duplicate] - javascript

This question already has answers here:
how to break the _.each function in underscore.js
(11 answers)
Closed 9 years ago.
If you have:
var some = [0,1,2,3];
_.forEach(some, function (val) {
if(val === 1) {
// this return does nothing
return;
}
});
Looking at the underscore source you can break out of forEach using
var breaker = {};
However breaker is not released to public scope and appears to be an internal variable.

you can use some instead of forEach, which will stop it the first time you return something non-falsy.
The opposite is every(), where it stops when you return something falsy.
You still have to pass the data using closure, since .some() will return true or false.
var some = [0,1,2,3];
_.some(some, function (val, index) {
if(val === 1) {
// this return does nothing
alert("exiting at step "+index+" from finding "+val);
return true;
}
alert("continuing at step "+index+" found "+val);
});

Related

Call a function according to its string name [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed last year.
I have a code which would be very repetitive, which according to the name of the string of an array executes one function or another.
I give an example of a code as I could do it.
// I use underscore in NodeJS
_.each(refresh, (value, key) => {
if(key === 'station') {
station.add({ id: value });
} else if(key === 'concentrator') {
concentrator.add({ id: value });
} else if....
});
It is possible to run the function according to your string to avoid so much checking with IF, etc.
[key].add({ id: value });
I have been watching several hours on the internet about the use of call, apply, etc; but I do not understand how it works well, perhaps because my knowledge of Javascript is not advanced.
Thanks !
Creating an anonymous function on an object is the best approach. As you can use the key to call the method.
Here is an example in code pen:
https://codepen.io/liam-hamblin/pen/KKyapNP
The code above takes in the key used to assign the function and does not require any checks. However, it is always the best approach to check that the key exists before calling.
const operations = {};
operations.add = (obj) => {
document.write("add - ");
document.write(JSON.stringify(obj));
}
operations.subtract = (obj) => {
document.write("subtract - ");
document.write(JSON.stringify(obj));
}
const input = prompt("Enter Function Name, type either subtract or add");
if (operations[input]) {
operations[input]({id:1});
} else {
document.write("no matching method")
}

Return code in an if statement is not running, but if I change it to the return variable, it is running. (Vanilla Javascript) [duplicate]

This question already has answers here:
forEach/for...in not returning values? [duplicate]
(5 answers)
Closed 4 years ago.
I have a function for a game I am creating:
var getFireableLaser = function() {
var result = null;
lasers.forEach(function(aLaser) {
if(aLaser.y <= -120) {
result = aLaser;
}
});
return(result);
}
it goes through an array of 'laser' objects and returns one when the if condition is met, however if i write the code like this:
var getFireableLaser = function() {
lasers.forEach(function(aLaser) {
if(aLaser.y <= -120) {
return(aLaser);
}
});
return(null);
}
the function only returns null? Why is it that when I do var laser = getFireableLaser(); in another function expression, laser is null when i console.log it? (in that specific other function);
When I console.log(aLaser) just before I return it, it shows the laser object.
So why is it that the returned object is null and saved as null?
forEach ignores whatever you return to it - returning from it doesn't break out of the forEach and return from the outer function, it simply stops the current iteration and goes onto the next iteration.
You might use .find instead:
var getFireableLaser = function() {
return lasers.find(aLaser => aLaser.y <= -120);
}
(though, .find returns undefined, not null, when a match isn't found)

Is there a way to return from the containing block of a map in Javascript? [duplicate]

This question already has an answer here:
Break statement in javascript array map method [duplicate]
(1 answer)
Closed 5 years ago.
I'm trying to implement a function which checks whether a list of letters are all present in a word.
function wordHasLatters(word,letters){
let wordChars={};
word.split("").map(c=>wordChars[c]=true);
let ok=true;
letters.split("").map(l=>ok=ok&&(wordChars[l]!=undefined));
return ok;
}
It is all relatively elegant with using maps. What bothers me is that I cannot return from the second map if I detect that a letter is not present. So I have to use a variable and return this. This is two extra lines in the code.
Is there a way to optimize this code?
const wordHasLetters = (word,letters) => letters.every(letter => word.includes(letter));
or use a plain old for loop:
function wordHasLetters(word, letters){
const hash = {};
for(var char of word)
hash[char] = true;
for(var letter of letters)
if(!hash[letter]) return false;
return true;
}
Or using a Set:
function wordHasLetters(word, letters){
const set = new Set(letters);
for(var char of word){
set.delete(char);
if(!set.size) return true;
}
return false;
}

How to detect that a multi-level object has an undefined or null property? [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 6 years ago.
In many places in my code, I have checks similar to the one below. It's very verbose, and ugly. Is there is better way? FYI, I'm using Lodash in all my projects, so I have access to that powerful library.
if (myAssessments[orderId].report &&
myAssessments[orderId].report[categoryProductCode] &&
myAssessments[orderId].report[categoryProductCode].categories &&
myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId]) {
// Do something related to
// myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId]
}
Since you use lodash, you might use the has method:
_.has(obj,[orderId, 'report', categoryProductCode, 'categories', comment.categoryId])
https://lodash.com/docs/4.16.6#has
Or the get method to get the value of the object path: https://lodash.com/docs/4.16.6#get
Not elegant way but you can wrap in try catch
var result;
try{
result = myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId]
}catch{}
if (result){
// do it
}
Use the built-in isset function:
if (isset(myAssessments[orderId].report) &&
isset(myAssessments[orderId].report[categoryProductCode]) &&
isset(myAssessments[orderId].report[categoryProductCode].categories) &&
isset(myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId)]) {
You could use an array with all properties to check and iterate until all properties have been checked.
function checkProperties(object, keys) {
return keys.every(function (key) {
if (key in object) {
object = object[key];
return true;
}
});
}
// usage
if (checkProperties(myAssessments, [orderId, 'report', categoryProductCode, 'categories', comment.categoryId])) {
// Do something related to
// myAssessments[orderId].report[categoryProductCode].categories[comment.categoryId]
}
I have this genric function
function chckForKeyPresence(data, arr, checkLength){
var currData = data;
for(var i=0; i<arr.length; i++){
if(!currData.hasOwnProperty(arr[i]))
return false;
currData = currData[arr[i]];
}
if(checkLength)
if(currData.length==0)
return false;
return true;
}
Here 1st argument is the main data, 2nd argument is the array of properties you need to check and the third argument will check the length of the last element that it is 0 or not, it will check only if the third argument is true.
You can use it like:
if(!chckForKeyPresence(data, ["results", "tweets"], true)){
// error
return;
}

How to search for a value in an Array of JavaScript? [duplicate]

This question already has answers here:
Best way to find if an item is in a JavaScript array? [duplicate]
(8 answers)
How can I check if an object is an array? [duplicate]
(51 answers)
Closed 7 years ago.
I am learning JavaScript and i came across this problem. I want to catch an input value using document.formName.elementName.valueand compare that value with an instance of an Array object.If the value exists it will throw an alert!.
You can use the indexOf() function you simply do this :
array.indexOf("string")
It will return -1 if the item is not found, otherwise just the position.
Here's a link W3Schools.
I think that has been asked thousands of times:
if(myFancyArray.indexOf(document.formName.elementName.value) !== -1){
alert("You did something wrong!");
}
Watch out as old versions of IE don’t know indexOf. (but who needs IE?)
Use indexOf
function search(arr,obj) {
return (arr.indexOf(obj) != -1);
}
Test cases:
search(["a","b"], "a"); // true
search(["a","b"], "c"); //false
You can add a convenience method to JavaScript's Array
Array.prototype.includes = function(element) {
var found = false;
for (var i = 0; i < this.length; i++) {
if (this[i] == element) {
found = true;
}
}
return found;
}
And, then, you can use below code to get some syntactic sugar
var myArray = [0,1,"hello","world"];
console.log(myArray.includes("hello")); //prints true
console.log(myArray.includes(10)); //prints false

Categories