2

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));
Tushar
  • 85,780
  • 21
  • 159
  • 179

3 Answers3

9

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

dotnetom
  • 24,551
  • 9
  • 51
  • 54
4

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));
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • This will break if there is no duplicate in data, eg: var data = [{ "name": "abc", "label": "xyz" }, { "name": "hello", "label": "world" }]; for this it will return only 1 object http://jsfiddle.net/renjithgovind/f1qb7xjc/ – user3501613 Aug 09 '18 at 17:29
  • @user3501613 This code I wrote 3 years ago just sucks. Try this instead: http://jsfiddle.net/fvLhx1o3/ – dfsq Aug 09 '18 at 19:19
  • thanks @dfsq, i think this findIndex won't work in IE and all,thats why i preferred grep,please give me any solution instead of findIndex – user3501613 Aug 10 '18 at 05:37
1

This is because these two objects are distinct, even though all the attributes inside are the same. You can see this from:

console.log(result[0] === result[2]);

which results in false.

Instead, you need to iterate through your array based on a unique identifier, such as name & label as such:

for(var i = 0, i < results.length; i++) {
    if (result[i].name === ... && result[i].label === ...) {
        index = i;
        break;
    }
}

to check if your item is unique.

David Li
  • 1,250
  • 8
  • 18