0

I have 2 arrays, one with 2 items and one with 5 items. The thing is I am trying to compare the descriptions of each item from the 1st array with decsriptions of each item in 2nd array.And I am doing the comparison by one of the free text similarity api.For the result I like to have two arrays with 5 items for the variable I created (allSimilarity). But when I run this code it executes 2 arrays with 10 items. I would like to know how I can fix this?

So I wrote the below code for that:

let allSimilarity=[]
const newIdeas=[{title:"Idea 1",description:"some text 1"},{title:"Idea 2",description:"some text 2"}]
const oldIdeas=[{title:"Idea 1",description:"some text 4"},{title:"Idea 2",description:"some text 3"},{title:"Idea 3",description:"some text 1"},{title:"Idea 4",description:"some text 2"},{title:"Idea 5",description:"some text 5"}]
newIdeas.forEach(item=>{
allSimilarity=[]
oldIdeas.forEach(async(oldIdea)=>{
    let text1=item.description.split(" ").join("%20") + "%20";
 let text2=oldIdea.description.split(" ").join("%20") + "%20";
//Here I am calling the api
  this.compareIdeas({text1,text2}).then((resp)=>{
    let similarity=resp
    allSimilarity.push({similarity,oldIdea:oldIdea.title,newIdea:item.title})
  })
})
console.log("This is all similarity",allSimilarity);
//Then I want to do some other method
})
FFXX
  • 95
  • 8
  • May not solve your actual problem, but you should call ```console.log()``` within your ```.then()``` function. – Tim Jul 23 '21 at 14:11
  • 1
    Don't use forEach with promises at all. See https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Estus Flask Jul 23 '21 at 16:09

0 Answers0