Here we are gonna see how to remove duplicates from JS array in either of the below format,
This method loops through your original array and finds the duplicate items and removes them and updates the non-duplicate items into the new array.
hashOwnProperty() is a method that returns a boolean value indicating whether the object has a property with the name of the argumet that is passed in the method. This method helps to scrutinize the array to find duplicates. For Example,
This method sorts the array first and then removes each element equal to the preceding one.
In the above array, we can see there is a duplicate name "BMW". So, We can use the iterative method to solve this effectively.
- Duplicates in an Array (or)
- Duplicates in an Array of Objects
Duplicates in an Array
Assume you have duplicates in a list of the country array,var countries=["China","India","United States","Indonesia","India","Pakistan"];
As you can see in the above array, country India is repeating twice from the list. In order to get an accurate unique country list, you can use any of the following methods.- jQuery
- Hashtables
- Sort
jQuery
See the Pen Remove Duplicates in an array using jQuery by Prime Study Hub (@PrimeStudyHub) on CodePen.
Hashtable
See the Pen Remove Duplicates in an array using Hashtable by Prime Study Hub (@PrimeStudyHub) on CodePen.
hashOwnProperty() is a method that returns a boolean value indicating whether the object has a property with the name of the argumet that is passed in the method. This method helps to scrutinize the array to find duplicates. For Example,
function uniq(a) { var found = {}; return a.filter(function(item) { return found.hasOwnProperty(item) ? false : (found[item] = true); }); }
Sort
See the Pen Remove Duplicates in an array using Sort by Prime Study Hub (@PrimeStudyHub) on CodePen.
This method sorts the array first and then removes each element equal to the preceding one.
Duplicates in an Array of Objects
var cars = [ { name: "Ford", models: ["Fiesta", "Focus", "Mustang"] }, { name: "BMW", models: ["320", "X3", "X5"] }, { name: "Fiat", models: ["500", "Panda"] }, { name: "BMW", models: ["320", "X3", "X5"] } ];
In the above array, we can see there is a duplicate name "BMW". So, We can use the iterative method to solve this effectively.
function uniqCars(a, param) { return a.filter(function(item, pos, array) { return ( array .map(function(mapItem) { return mapItem[param]; }) .indexOf(item[param]) === pos ); }); }
See the Pen Remove duplicates in an array of objects by Prime Study Hub (@PrimeStudyHub) on CodePen.
Comments