Let's say we have the following data:
const names = [
{name: 'Spiros', contry: 'š¬š·'},
{name: 'Bjorn', contry: 'š©š°'},
{name: 'Theo', contry: 'š¬š·'},
]
The problem
We want to loop through the names array and:
- print the county flag for the name
Bjorn - stop the loop when we found what we were searching for.
With a classical for loop, we could do this very easily by using the Javascript break keyword:
for (const n of names) {
if (n.name === 'Bjorn') {
console.log(n.flag)
break;
}
}
However, if we try to do the same with a forEach loop we will get an error:
names.forEach(n => {
if(n.name === 'Bjorn') {
console.log(n.flag)
// āļø this will not work
// Uncaught SyntaxError: Illegal break statement
break;
}
})
The reason for the Uncaught SyntaxError: Illegal break statement is that the break statement works only within loops and forEach() is a function.
The solution
There are multiple ways to use forEach() and stop when we found want we are searching for.
In my opinion, the best fix for this using the Array.find() method:
const result = names.find(n => n.name === 'Bjorn')
result.flag // š©š°
Keep in mind that find() will end after finding the first result, exactly as a break statement will do:
// ā ļø find will return ONLY the first result
const result = names.find(n => n.flag === 'š¬š·')
result // {name: 'Spiros', contry: 'š¬š·'}
If we want to get the index of the first result we can use Array.findIndex():
const index = names.findIndex(n => n.name === 'Theo')
index // 3
You can checkout the full code on Github, and here is the live example.
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js