Return repeated elements within an array

Asked

Viewed 113 times

3

How to pick up only the repeated elements within an array?

I have for example:

let array = [1, 2, 2, 2, 3, 3, 4, 4, 5, 6, 8, 8, 9, 9];

And I want to return all duplicates to get:

[2, 3, 4, 8, 9 ]

If I used the [...new Set(array)] he would return:

[1, 2, 3, 4, 5, 6, 8, 9 ]
  • 1

    Good friend, you can use the filter to bring all duplicated values const arrayFilter = array.filter((item, index, array) => array.indexOf(item) !== index // [2,2,3,3,4,4,8,8 ...] and if you only want to bring a single repeated value you can use the new Set const duplicates = [...new Set(arrayFilter )]

  • 1
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.