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

This demo will demonstrate how our code can remove duplicate elements from array.

You may also like –

Tagged in:

,

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles