Finding Non-Unique Values in an Array
Identifying duplicate values in a JavaScript array is a common task. While iterating through the array and comparing each element to the others might seem like a straightforward approach, it can be inefficient, especially for large arrays.
One optimized solution involves sorting the array first. This step reduces the complexity from O(n^2) to less than O(n^2) by grouping similar elements together.
Once the array is sorted, you can iterate through it and check if the current element matches the next or previous element. If they are the same, the value is considered a duplicate and can be added to a results list.
const findDuplicates = (arr) => { let sorted_arr = arr.slice().sort(); let results = []; for (let i = 0; i < sorted_arr.length - 1; i++) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } return results; };
For example, given an array like [9, 9, 111, 2, 3, 4, 4, 5, 7], this approach would efficiently identify and return the duplicate values: [9, 4].
By leveraging sorting and comparing adjacent elements, this solution offers a time-efficient method for finding non-unique values in an array.
The above is the detailed content of How Can I Efficiently Find Duplicate Values in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!