How to remove duplicate elements from JavaScript Array?

  • Share this:

To remove duplicate elements from a JavaScript array, you can use the `Array.prototype.filter()` method in combination with the `indexOf()` method.

Here is an example:

function removeDuplicates(arr) {
  return arr.filter((item, index) => arr.indexOf(item) === index);

const numbers = [1, 2, 3, 3, 4, 5, 5];
const uniqueNumbers = removeDuplicates(numbers);
console.log(uniqueNumbers);  // [1, 2, 3, 4, 5]

This function first uses the `filter()` method to iterate over the array and keep only those elements for which the `indexOf()`  method returns the same value as the current index. The `indexOf()` method returns the first index at which a given element can be found in the array, or -1 if it is not present. Therefore, by using this method, we can filter out all duplicates, because they will have a different index than the original element.

Note: this method only works for arrays containing primitive data types (such as numbers or strings). If the array contains objects, you will need to use a different approach to remove duplicates, such as creating a new array and adding only those objects that are not already present in the array.


About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.