How to remove duplicate elements from array in JavaScript?

Total
0
Shares
How to remove duplicate elements from array in JavaScript?

In this article we are going to create a function to remove duplicate elements from javascript array. Our function will be able to handle strings and numbers inside the provided array. Check out the code –

var arr = ["a", "b", "a", 1, 2, 1, 1, 2];

const removeDuplicates = (myArr) => {
  var uniqueArr = [];

  myArr.forEach((val) => {
    if (typeof val === "number" || typeof val === "string") {
      if (!uniqueArr.includes(val)) {
        uniqueArr.push(val);
      }
    }
  });

  return uniqueArr;
};

    Tweet this to help others

Here we have created a function removeDuplicates(). It accepts one parameter – our array containing duplicate elements and returns the non-duplicate array.

This function loops over all the elements of input array using forEach. We are using the ES6 format for writing our code. Each element is checked if it is number or string using typeof operator of JS.

In the next step (within loop) we are checking if the element is already included in our temporary array, uniqueArr. We are using includes() function for that. Finally, it returns the clean array with non-duplicate values.

Live Demo

Open Live Demo

You may also like –