Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get all repeated values from an array to a new array

I’m trying to filter the given array to a new array with ONLY repeating numbers:

const array = [1, 1, 1, 2, 3, 4, 5, 6, 7, 7, 8, 8, 2, 2, 2, 2, 2, 2, 2, 1, 1];

I tried this code:

const findDuplicates = (arr) => arr.filter((item, index) => arr.indexOf(item) !== index);

But the output that I’m getting is this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[1, 1, 7, 8, 2, 2, 2, 2, 2, 2, 2, 1, 1]

As you can see that in this array there are missing numbers. It should be like this:

[1, 1, 1, 7, 7, 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1]

What I’m doing wrong?

>Solution :

You could check the value with value at previous index or next index.

const
    array = [1, 1, 1, 2, 3, 4, 5, 6, 7, 7, 8, 8, 2, 2, 2, 2, 2, 2, 2, 1, 1],
    result = array.filter((value, i, { [i - 1]: prev, [i + 1]: next }) =>
        prev === value || value === next
    );

console.log(...result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading