Remove duplicates from a JavaScript Array

In JavaScript, you may combine the indexOf() method and the filter() method to get rid of duplicates from an array

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

let numbers = [1, 2, 3, 3, 4, 4, 5];
let uniqueNumbers = removeDuplicates(numbers);

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

The removeDuplicates() function in this code accepts an array as an argument and produces a new array that is empty of duplicates. This is accomplished by creating a new array with the filter() method that only contains elements that are unique within the original array.

A callback function is provided as an argument to the filter() method, which is used to filter each element of the array. By comparing the current element's index to the output of executing indexOf() on the original array, the callback function determines if the current element exists only once in the array. The element is added to the new array if the two indices are equivalent, which indicates that it is not a duplicate of any other element.

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Difference between Validations, Callbacks and Observers