Languages
[Edit]
EN

JavaScript - find duplicates in array

0 points
Created by:
MindOfMadness3
696

In this article, we would like to show you how to find duplicates in array using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const array = [1, 2, 3, 2, 3, 3];

const sortedArray = array.slice().sort();

let result = [];

for (let i = 0; i < sortedArray.length - 1; ++i) {
    if (sortedArray[i + 1] === sortedArray[i]) {
        result.push(sortedArray[i]);
    }
}

console.log('Duplicate elements: ' + result);

 

Practical example

In this example, we create a reusable arrow function that sorts the array and then checks if the next item in the array is the same as the previous one to find the duplicates.

// ONLINE-RUNNER:browser;

const findDuplicates = (array) => {
    const sortedArray = array.slice().sort();
    let results = [];
    for (let i = 0; i < sortedArray.length - 1; ++i) {
        if (sortedArray[i + 1] === sortedArray[i]) {
            results.push(sortedArray[i]);
        }
    }
    return results;
}


// Usage example:

const numbers = [1, 2, 3, 2, 3, 3];

const duplicates = findDuplicates(numbers);

console.log('Duplicate elements: ' + duplicates);

See also

  1. JavaScript - remove duplicates from array

References

  1. Array.prototype.sort() - JavaScript | MDN

Alternative titles

  1. JavaScript - get duplicates from array
  2. JavaScript - get duplicate elements from array
  3. JavaScript - get non-unique values from array
  4. JavaScript - checking for duplicate elements in array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join