How to Remove Duplicate Object from Array in JQuery?

By Hardik Savani July 3, 2023 Category : Javascript jQuery

Today, our topic is how to remove duplicates items from multidimensional array in jquery. i will help to remove duplicates from an array of objects in javascript. it's very simple to delete duplicate object from json array in jquery.

After long time i am writing small jquery post for jquery array. i always prefer to write every topic that might be help to other developer. same point of view i am going to write this small post for how to remove duplicates object or array from array.

In this example we will create one helper function called "removeDumplicateValue()". in this function we use each loop remove duplicate items from array and create new array. you can see very small and basic example for this.

Example:

<!DOCTYPE html>

<html>

<head>

<title>Remove Duplicate Objects from Array Jquery Example - ItSolutionstuff.com</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>

<body>

<script type="text/javascript">

var myArray = [

{ "id" : "1", "firstName" : "Hardik", "lastName" : "Savani" },

{ "id" : "2", "firstName" : "Vimal", "lastName" : "Kashiyani" },

{ "id" : "3", "firstName" : "Harshad", "lastName" : "Pathak" },

{ "id" : "1", "firstName" : "Hardik", "lastName" : "Savani" },

{ "id" : "5", "firstName" : "Harsukh", "lastName" : "Makawana" }

];

function removeDumplicateValue(myArray){

var newArray = [];

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

var exists = false;

$.each(newArray, function(k, val2) {

if(value.id == val2.id){ exists = true };

});

if(exists == false && value.id != "") { newArray.push(value); }

});

return newArray;

}

console.log(removeDumplicateValue(myArray));

</script>

</body>

</html>

Output:

Array(4)

0: {id: "1", firstName: "Hardik", lastName: "Savani"}

1: {id: "2", firstName: "Vimal", lastName: "Kashiyani"}

2: {id: "3", firstName: "Harshad", lastName: "Pathak"}

3: {id: "5", firstName: "Harsukh", lastName: "Makawana"}

I hope it can help you...

Shares