Remove duplicate from array within array

You can check if an element exists prior to using push. Lots of ways to approach this, but an easy solution might be:

Array.prototype.pushUnique = function pushUnique(item) {
  if (this.indexOf(item) === -1) {
    this.push(item);
  }
}

// Then use it...
const arr = [];

arr.pushUnique("Family Practice");
// arr = ["Family Practice"]

arr.pushUnique("General Practice");
// arr = ["Family Practice", "General Practice"]

arr.pushUnique("Family Practice");
// arr = ["Family Practice", "General Practice"]

Not sure if that answers what you’re after, but in general best bet is to just use indexOf or includes prior to adding to the array.

Leave a Comment