Skip to main content

Remove Duplicates from JS array - [Solved]

Here we are gonna see how to remove duplicates from JS array in either of the below format,
  • Duplicates in an Array (or)
  • Duplicates in an Array of Objects
Let's go through each in detail.

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

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.

Hashtable


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


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
    );
  });
}








Comments