0

I make two api call and I need to compare the results and create a new array that contains only the values of the second call that are not equals to first

  const listaRealmTrovata = async () => {
    await axios.get(APICALL1)
      .then((realmUserAttivi) => {
        axios.get(APICALL2)
          .then((realmAttivi) => {
            realmUserAttivi.data.map((realmUserAttivo) => {
              realmAttivi.data.filter((res) => {
                if (realmUserAttivo.realm.id !== res.id) {
                  setListaRealm(previousListRealm => [...previousListRealm, { value: res.id, label: res.realmId }]);
                }
              })
            })
          })
      })
  };

In this way I obtain a list with with repeated values, because I compare each element of the first array each time with the elements of the second array

Example:

 realmUserAttivi.data : [
   0: {id:1}
   1: {id:2}
   3: {id:3}
]

 realmAttivi.data : [
   0: {id:1}
   1: {id:5}
   3: {id:3}
]

so the result that I would to obtain is:

listaRealm: [0: {id:5}] // the only one that isn't in equal in the two array.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Jack23
  • 1,368
  • 7
  • 32

3 Answers3

0

Here the variable notPresent will contain data from realmAttivi which is not found in realmUserAttivo.

//api call code
.then((realmAttivi) => {
    const notPresent = realmAttivi.filter(ra => !realmUserAttivo.some(rua => rua.id === ra.id));
    setListaRealm(previousListRealm => [...previousListRealm, ...notPresent]);
})
James
  • 20,957
  • 5
  • 26
  • 41
0
 realmUserAttivi = [
   {id:1},
   {id:2},
   {id:3},
]

 realmAttivi = [
   {id:1},
   {id:5},
   {id:3}
]      


const notRepeated = (arr1, arr2) => 
  arr2.filter(objArr2 => !arr1.find(objArr1 => objArr2.id == objArr1.id))

notRepeated(realmUserAttivi,realmAttivi)

this will return [{id:5}]

Itay S
  • 73
  • 7
0

I thought if the array become huge , since the algorithm being used is n^2 ,it might freeze the page, since JS would be busy ,tried making it async .

let realmUserAttivi = [
   {id:1},
   {id:2},
   {id:3},
],
 realmAttivi = [
   {id:1},
   {id:5},
   {id:3}
    ]  
async function findCommon() {
    let promises = []
    for (let i = 0; i < realmAttivi.length; i++)
    {
       promises.push(SetTimoutPromise(i))
    }
    let res = await Promise.all(promises)
    res = res.filter(e => e)
    return res
}


 let SetTimoutPromise =(index)=> new Promise((resolve, reject) => {
             setTimeout(() => {
                if (!realmAttivi.find((objArr1 => realmUserAttivi[index].id == objArr1.id)))
                {
                    resolve(realmAttivi[index])
                }
            resolve()
        },0)
    })
findCommon()
Ankush Verma
  • 689
  • 1
  • 8
  • 17