Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Duplicate object from array in jquery code not working

This is my array in jquery , which contains duplicate objects/elements :

[{
    "name": "hello",
    "label": "world"
}, {
    "name": "abc",
    "label": "xyz"
}, {
    "name": "hello",
    "label": "world"
}]

I am using the following piece of code to remove duplicate elements but it not working the duplicate elements are not removed.

var result = [];

$.each(subservices, function (i, e) {
    if ($.inArray(e, result) == -1)
        result.push(e);
});

alert(JSON.stringify(result));
like image 906
Shivkumar Mallesappa Avatar asked Nov 16 '25 04:11

Shivkumar Mallesappa


2 Answers

Function $.inArray works fine for simple types (e.g. number or string), but for complex types it does not produce the correct result, because it tries to match by reference. Instead of using inArray in your loop you can search the array using function grep:

var subservices = [{
        "name": "hello",
        "label": "world"
    }, {
        "name": "abc",
        "label": "xyz"
    }, {
        "name": "hello",
        "label": "world"
    }
];

var result = [];
$.each(subservices, function (i, e) {
    var matchingItems = $.grep(result, function (item) {
       return item.name === e.name && item.label === e.label;
    });
    if (matchingItems.length === 0){
        result.push(e);
    }
});

//displays result [{"name":"hello","label":"world"},{"name":"abc","label":"xyz"}]
alert(JSON.stringify(result));

Here is a working jsFiddle

like image 77
dotnetom Avatar answered Nov 18 '25 18:11

dotnetom


You need to filter array by unique name/value. Here is some pure JS solution:

var data = [{
    "name": "hello",
    "label": "world"
}, {
    "name": "abc",
    "label": "xyz"
}, {
    "name": "hello",
    "label": "world"
}];

var result = data.filter(function(el, i, x) {
    return x.some(function(obj, j) {
        return obj.name === el.name && (x = j);
    }) && i == x;
});

alert(JSON.stringify(result, null, 4));
like image 44
dfsq Avatar answered Nov 18 '25 20:11

dfsq