0

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.

2 Answers 2

3

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});
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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) {
    ....
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.