In: Computer Science
I want to compare a string with the previous strings in a forEach loop using javascript.
So im accessing data from an API. Im iterating through them using a forEach() loop. I want to compare the current 'title' string from the api with all previous title strings its pulled. The title is located under article.title
fetch(req)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
data.articles.forEach((article) => {
}
If the title matches any other title used already id like to skip the entire iteration.
To do this you have to maintain a list of all the title used so far and in the then part of the fetch request you have to compare with all the elements in fetch data and take action accordingly
Here is the solution
JAVASCRIPT
let titlesUsedSoFar=[] //to maintain a list of titles used so
far
fetch(req)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
data.articles.forEach((article) => {
let flag=false; //flag to check if variable
exists
//for loop to check if the title already pulled from
api
for(let i=0;i<titlesUsedSoFar.length;++i)
{
if(titleUsedSoFar===article.title)
{
flag=true; //set
flag = true if it exists
}
}
if(flag==false) //if doesnt
exists
{
//add in
the titles list
//DO THE
PROCESSING YOU WANT TO DO HERE
titlesUsedSoFar.push(article.title);
}
else
{
//THIS
PART DO WHAT YOU WANT TO DO IF ALREADY TITLE PRESENT IN THE USED
LIST
}
}
}