Remove Duplicate Object from Array in JQuery?

In this tutorial explain of remove duplicates object from array in jquery. i will share topic for remove duplicate object from array.

it’s easy example to delete duplicate object from json array in jquery. In this example we will create one helper function called “removeDuplicateValues()”.in this function we use each loop remove duplicate items from array. you can easily understand example in article. 

You can follow below example to remove duplicate objects from array in jquery.let’s see example code.

Example:
var myData = [
    {"id" : "1", "rank" : "first"},
    {"id" : "2", "rank" : "second"},
    {"id" : "3", "rank" : "third"},
    {"id" : "1", "rank" : "first"},
    {"id" : "5", "rank" : "fifth"},
];

    function removeDuplicateValues(myData) {
        var newData = [];
        
        $.each(myData,function(key,val1){
            var existsData = false;
            $.each(newData, function(k, val2){
                if(val1.id == val2.id) { existsData = true };
            });
            if(existsData == false && val1.id !="") {
                newData.push(val1);
            }
        });
        
        return newData;
    }
    
    Console.log(removeDuplicateValues(myData));
Output:
Array(4)
0: {"id" : "1", "rank" : "first"}
1: {"id" : "2", "rank" : "second"}
2: {"id" : "3", "rank" : "third"}
3: {"id" : "4", "rank" : "fourth"}
Remove duplicate object from array using unique function.

Use $.unique() function of remove duplicate object from array in  using jquery, you can integrate $.unique() function.Here’s how you can do it.

Example:
var myDataValue = [
    {"id" : "1", "data" : "test"},
    {"id" : "2", "data" : "test1"},
    {"id" : "3", "data" : "test2"},
    {"id" : "1", "data" : "test"},
    {"id" : "5", "data" : "test3"},
];

$uniqueDataArray = $.unique(myDataValue);

console.log($uniqueDataArray);
Output:
Array(4)
0: {"id" : "1", "data" : "test"}
1: {"id" : "2", "data" : "test1"}
2: {"id" : "3", "data" : "test2"}
3: {"id" : "4", "data" : "test3"}

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *