How to Identify Duplicate Values Within an Array
The ability to identify and retrieve non-unique elements from a JavaScript array is a common programming task. Unlike removing duplicates, this process involves segregating values that appear multiple times.
Easiest Approach Using Sorting and Iteration
The simplest and efficient solution is to leverage the sorted version of the array. After sorting, compare consecutive elements:
function findDuplicates(arr) { let sortedArr = arr.slice().sort(); let duplicates = []; for (let i = 0; i < sortedArr.length - 1; i++) { if (sortedArr[i] == sortedArr[i + 1]) { duplicates.push(sortedArr[i]); } } return duplicates; }
This approach provides an efficient search with a time complexity of less than O(n2), where n is the array size.
Consider the example array [9, 9, 111, 2, 3, 4, 4, 5, 7]:
console.log(findDuplicates([9, 9, 111, 2, 3, 4, 4, 5, 7])); // Result: [9, 4]
The function captures the duplicate values, enabling you to identify the occurrences without retrieving the specific indices or frequency of repetition.
The above is the detailed content of How to Find Duplicate Values in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!