Home > Web Front-end > JS Tutorial > How Can I Efficiently Find Duplicate Values in a JavaScript Array?

How Can I Efficiently Find Duplicate Values in a JavaScript Array?

Susan Sarandon
Release: 2024-12-15 15:20:23
Original
367 people have browsed it

How Can I Efficiently Find Duplicate Values in a JavaScript Array?

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;
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template