Zuker
Zuker

Reputation: 456

Create an array in jquery and check if it's an element

After getting some data using ajax & json i've got this function

    if(data.length != 0) {
        var arreglo = new Array();
        $.each(data, function(index, data) {
            if (jQuery.inArray(data.id, arreglo) == -1) {
                arreglo.push(data.id);
                $("#envivo").append("<li>Titulo: " + data.titulo + " Link: " + data.link + " Fuente: " + data.fuente + "</li>");
            }
        });
    }
}
$(document).ready(function() {
    var fecha = Math.round((new Date()).getTime() / 1000);
    setInterval(function() {
        $.ajax({
            data: "fecha="+fecha,
            type: "GET",
            dataType: "json",
            url: "data.php",
            success: function(data){
                restults(data);
            }
        });
    }, 5000);
});

What i'm trying to do

  1. Check if any data it's retrieved from ajax
  2. Create an array to store data.id
  3. Loop inside the data from ajax
  4. Check if data.id it's in array created in [2]
  5. If id it's not in array, i save it into and apped some data

step 4 it's not working and part of the 5 (saving into array)

Any ideas?

Thanks in advance

Upvotes: 0

Views: 1372

Answers (2)

Guffa
Guffa

Reputation: 700680

I have tried your code, and it works just fine:

http://jsfiddle.net/Jfq6d/

You have to check that the data that you get actually looks the way that you expect. You can for example use the Net tab in the FireBug addon in Firefox to examine the response that you get in the AJAX call.

Edit:

As you want to reuse the function, you have to create the array outside the function:

var arreglo = [];

function restults(data) {
  if(data.length != 0) {
    $.each(data, function(index, data) {
      if (jQuery.inArray(data.id, arreglo) == -1) {
        arreglo.push(data.id);
        $("#envivo").append("<li>Titulo: " + data.titulo + " Link: " + data.link + " Fuente: " + data.fuente + "</li>");
      }
    });
  }
}

Upvotes: 0

Paul Perigny
Paul Perigny

Reputation: 973

The inArray function uses the identity compare operator (===).

This will cause problems if the data returned the id as a string, but you are interpreting is as a number.

"9" ==== 9 <- False

"9" == 9 <- True

Upvotes: 1

Related Questions