In this topic, When we working with arrays in JavaScript, it is common to encounter duplicate values. Duplicate values can cause problems in some cases, such as when performing calculations or comparisons on the array. Fortunately, JavaScript provides lot of methods to identify and remove duplicate values from an array. Here is the several Method to find duplicate values in a JavaScript array:
Using indexOf() Method
const arr = [1, 2, 3, 4, 2, 5, 1];
const duplicates = [];
for (let i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) !== i) {
duplicates.push(arr[i]);
}
}
console.log(duplicates);
// Output: [1, 2];
Using filter() Method
const array = [1, 2, 3, 4, 5, 5, 3, 6, 7];
const duplicates = array.filter(
(value, index) => array.indexOf(value)!== index);
console.log(duplicates);
// Output: [5, 3]
In above example, The filter() method allows you to create a new array that contains only the elements that pass a certain test. By using the filter method with a callback function that checks for duplicate elements, you can easily find the duplicates in an array.
Popular Posts
- Show / Hide div based on dropdown selected using jQuery
- Autosuggestion Select Box using HTML5 Datalist, PHP and MySQL with Example
- Infinite Scrolling on PHP website using jQuery and Ajax with example
- Custom Authentication Login And Registration Using Laravel 8
- How to Convert MySQL Data to JSON using PHP
- Google Login or Sign In with Angular Application
- How to change date format in PHP?
- Image Lazy loading Using Slick Slider
- Slick Slider Basic With Example
- php in_array check for multiple values
- Adaptive Height In Slick Slider
- Slick Slider Center Mode With Example
- How to Scroll to an Element with Vue 3 and ?
- JavaScript Multiple File Upload Progress Bar Using Ajax With PHP
- Slick Slider Multiple Items With Example
Total Views: 3,322