OneBite.Dev - Coding blog in a bite size

remove duplicates from an array in Javascript

Code snippet on how to remove duplicates from an array in Javascript

  let arr = [2, 3, 4, 2, 3];  
  let UniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);  
  console.log(UniqueArr); 

This code is to remove duplicates from an array in Javascript. The first line of code declares an array with duplicate elements. The second line calls the filter() method to filter out any duplicate elements. The filter compares each element in the array with its instance in the array using the indexOf() method. The filter returns all elements with an index that match the current iteration, and the output is printed on the console. So what the code does is, it loops through each element in the array, compares it with all other elements of the array using the indexOf() method, and returns only the unique elements in a new array.

javascript