Loop adding repeated values

Asked

Viewed 39 times

0

I have a loop inside a request, which adds an ID in an array, so that on the next repeat it checks if this same ID is no longer added. and if it is already in the array, skip to the next array id.

setInterval(all, 5000);
    
    function all{
        request(html[i], function(erro,resp,html)
        {
          var data = JSON.parse(html[i]);
          if(all_id[index] != data.live_id)
          {
            all_id.push(data.live_id)
            index++
                  
          }else{
           index++
          }
        } 
    }

But for some reason, my loop is not doing what I want, and ends up adding the same values making my ID check not work, as I can solve?

Na imagem da para ver o loop adicionando o valor 352919 duas vezes.

In the image of to see the loop adding again the same values but backward.

  • Why don’t you search first of then enter if there is no Ex.: if( all_id.findIndex(data.live_id) == -1 ) all_id.push(data.live_id)

  • It worked out! Thank you.

  • I’m glad it worked out!

1 answer

0


Instead of doing like this:

if(all_id[index] != data.live_id){
    all_id.push(data.live_id)
    index++
 }else{
    index++
  }

You the new function findIndex if you do not find it in your array, returns -1, and returns -1 is because you do not have it in your array and then you insert

Example:

if( all_id.findIndex(data.live_id) == -1 ) all_id.push(data.live_id)

I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.