Can add url to jQuery array and do some validation with it

I am new to jQuery / JS. But I have a loop in jQuery where I would like to do some validation. I would like to check if the url has already been typed or not. The data for the loop is from JSON, if that matters.

Basically, I would have an array var = myArray where I would put all urls from the loop. I go through this cycle with everyone. Then every time I check if the url is already in the array. As pseudo:

var myArray = [];
each data {
    myArray.push({'url':data.url});

    if data.url is already in myArray {
        do stuff
    }

    if data.url is not already in myArray {
        do other stuff
    }
}

      

I played aounrd with jQuery.inArray () but I always got -1

Thanks for your help!

+3


source to share


4 answers


In your pseudocode that you clicked on the array before checking if it exists so that it is always there. To do this, you need to press data.url

instead{'url':data.url}

A working example of what you are looking for:



var testData = [ 1, 2, 2, 3, 4]
var myArray = []    
jQuery.each( testData, function( pos, val ) {
    // not in array
    if ( jQuery.inArray( val, myArray ) == -1 ) {
        myArray.push( val );

    // in array  
    } else {
        alert( "Already in [" + myArray + "] : " + val );        
    }    
})​;​

      

+1


source


Just push url directly and don't create an object:

myArray.push(data.url);

      

Then it jquery.inarray()

should work just fine



if (jquery.inArray(data.url, myArray))

      

However, you will need to add the new url at the end of the loop, not at the beginning, otherwise they will always be in the array when you go to checkout.

Demo: http://jsfiddle.net/c2934/

+1


source


try this:

var myArray = [];
$.each(data, function(i,u) {
   if($.inArray(u, myArray)){
        //DO STUFF IF URL IN ARRAY
   }else{
       myArray.push(u);
       //DO SUTFF IF URL NOT IN ARRAY
   }
});

      

+1


source


You can also use $ .grep ()

var myArray = [];
var ar = [{'url':'test1'},{'url':'test1'},{'url':'test3'}];
$.each(ar,function(ii,data) {
  if ($.grep(myArray,function(e,i){ return e.url == data.url;   }).length > 0) {
    console.log('in array: ' + data.url);
  } else {
    console.log('not in array: ' + data.url);
  }
  myArray.push({'url': data.url });
});

      

0


source







All Articles