Psl
Psl

Reputation: 3920

Jquery code to find duplicates from an array

i have a json data .

data ={{"id":"10","name":"test"},{"id":"10","name":"test1"},{"id":"11","name":"tsst"},{"id":"41","name":"jhkj"},{"id":"11","name":"yuyyu"},}

from the json data i am fetching the id to get location from a database table as follows

data.each(function( index ) {
    var id = index.id //gets 10
                       //again gets 10 and again doing db operations for same id value 
    //db operations 
      //get location details from db using this id    
    // operations after getting locations....................

    });

my proble is id is repeated ie 10,10,11,41 ,11.so calling db operations for repeated values also.How can i avoid by calling db operations for repeated id values .

Upvotes: 0

Views: 5146

Answers (4)

4b0
4b0

Reputation: 22323

Check for duplicate ID may solve your problem.

For Example:

var dup= {};
data.each(function( index ) {
    var id = index.id;
    dup.push(id);
    if (dup[id])
        $(this).remove(); //OR DO nothing
    else
     //Your DB Operation

});

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

Try

var temp = {};
for(var i = 0; i < data.length ; i++ ){
    var obj = data[i];
    if(temp[obj.id] >= 0){
        data.splice(i, 1);
        i--;
    }
    temp[obj.id] = i;
}
console.log(data)

Demo: Fiddle

Upvotes: 3

Sunil Verma
Sunil Verma

Reputation: 2500

Create another array and add the value in it after checking that it exists or not.

you can use inArray ref : http://api.jquery.com/jQuery.inArray/ for this purpose.

Upvotes: 0

Alex
Alex

Reputation: 11579

I think you have to avoid to call DB operations for all id in the loop. Just pass everything to backend and get data for all id which you need within one DB operation.

Upvotes: 0

Related Questions