In this article, we are going to discuss “How to Find Duplicate Elements in a Given Array?”. Duplicate elements could be a great problem, so finding these kinds of elements becomes necessary, and also in many JS interviews, this can come into frame as a question. As a developer and a JS beginner, we should have answer of this question.
So the basic solution is to find duplicates in an array, we can make use of the array filter method. Filter method is the easiest way to find out to solve this problem. Filter basically, takes 3 parameters, element, index, and array on which filter is applied. Then we can check for the indexOf each element and return whichever does not match with the index.
Let’s see a basic program to understand:
<script> const duplicatedArray = [14,23,5,6,6,23,89]; const duplicates = duplicatedArray.filter((ele,index,arr)=>arr.indexOf(ele)!= index); console.log(duplicatedArray); console.log(duplicates); </script>
Okay, so we have our basic code to understand filter, here we have an array with two duplicate values 23 and 6. So the objective is to find the number which are present in an array multiple times. For that, we have added another constant named duplicates in which we have added duplicatedArray.filter() method. In this method, we added a callback function with initial parameters like (ele, index and arr).
ele holds value of the elements, then index will hold index value of element, and lastly arr is our array which is targeted. In this callback, we added
arr.indexOf(ele)!=index which means we will check the matching indexes of element with index, and we will get the value of these indexes in a new array.
(7) [14, 23, 5, 6, 6, 23, 89] (2) [6, 23]