Removing the duplicates in the array of the objects is always tricky and sometimes it can be more complex, when we are going with an array of array.
Recently, I came across the scenario, where the duplicate employees are pushing into the array, when some process is going on, so that I need to write a client side jQuery script to clean up the array; i.e., removing the duplicate entries.
Code
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <meta charset="utf-8" />
- <script src="https://code.jquery.com/jquery-3.0.0.js" ></script>
- </head>
- <body>
- <script type="text/javascript">
- var Array = [{ "Name": "Bob Ross", "EmpID": "0441" },
- { "Name": "Ram", "EmpID": "0442" },
- { "name": "Bob Ross", "EmpID": "0441" },
- { "name": "Pradeep", "text": "0443" },
- { "name": "Ram", "text": "0442" }];
-
- ArrayArray = Array.reduce(function (item, e1) {
- var matches = item.filter(function (e2)
- { return e1.EmpID == e2.EmpID});
- if (matches.length == 0) {
- item.push(e1);
- }
- return item;
- }, []);
-
- console.log(Array);
- </script>
- </body>
- </html>
Result
There are many methods available to remove the duplicate values from an array but from the scenario I came across, I found this is the most efficient and generic way to work on it.
I hope you enjoyed this blog. Your valuable feedback, questions or comments about this blog are always welcome.