Mauro74
Mauro74

Reputation: 4826

Removing duplicates from a json object

I'm looping through an json-like object and I'm trying to exclude a duplicate entry (the one with id:1) with no success. Here's my code:

var productData = '[{"id":1,"name":"Retro","price":10,"color":"blue"},{"id":2,"name":"Designer","price":12,"color":"red"},{"id":3,"name":"Classic","price":14,"color":"yellow"},{"id":1,"name":"Retro","price":10,"color":"blue"},{"id":4,"name":"Rimless","price":14,"color":"purple"},{"id":5,"name":"Glam & Sparkle","price":8,"color":"grey"}]',
    data = $.parseJSON(productData),
    table = $("#productTable"),
    dataFiltered = [];

$.each(data, function(key, value) {

    if ($.inArray(value.id, dataFiltered) === -1) {

        dataFiltered.push({"id": value.id, "price": value.price, "name": value.name,"color": value.color});


    }
});

console.log(dataFiltered)

$.each(dataFiltered, function(key, value) {
        table.append("<div class='row'><span>&pound;"+value.price+"</span>"+
                     "<span>"+value.name+"</span>"+"<span>"+value.color+
                     "</span></div>");
});

What am I doing wrong? It returns the same object with the duplicate entry in it. here's the fiddle demo too.

Thanks in advance.

Upvotes: 0

Views: 979

Answers (2)

Raghuveer
Raghuveer

Reputation: 2638

Try this JSFIDDLE

Not sure whether this is the optimal way or not.. :)

var ids = []; 
$.each(data, function(key, value) {
    if($.inArray(value.id, ids) === -1){
        ids.push(value.id);
        dataFiltered.push({"id": value.id, "price": value.price, "name": value.name,"color": value.color});
    }
});

Upvotes: 3

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10153

Your problem is here: $.inArray(value.id, dataFiltered). value.id is an integer. dataFiltered is an array of objects. $.inArray does this

for(i = 0; i < dataFiltered.length; i++) { 
    if(value.id === dataFiltered[i]) return 'found'; 
}

so it is comparing an integer to some objects. Obviously won't find anything ever.

What you need to do is implement a find function:

function arrayFind(a, v, check) {
    var i;
    for(i = 0; i < a.length; i++) {
        if(check.call(this, a[i], v)) {
            return true; 
        }    
    }
    return false;
}

and use it like this:

var findById = function(item, value) {
    return item.id === value;
};

if (arrayFind(dataFiltered, value.id, findById) === false) {
    .... 
}

Try looking at lodash for a more cool implementation.

Also, to better understand the difference, using my arrayFind implementation, your code would look like this:

var findById = function(item, value) {
    return item === value; // your issue is here
};

if (arrayFind(dataFiltered, value.id, findById) === false) {
    ....
}

Upvotes: 0

Related Questions