Home > Blockchain >  Get all repeated values from an array to a new array
Get all repeated values from an array to a new array

Time:04-25

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:

[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?

CodePudding user response:

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);

  • Related