Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

后端 未结 30 3160
再見小時候
再見小時候 2020-11-21 04:35

I need to check a JavaScript array to see if there are any duplicate values. What\'s the easiest way to do this? I just need to find what the duplicated values are - I don\'

30条回答
  •  -上瘾入骨i
    2020-11-21 05:18

    Here is mine simple and one line solution.

    It searches not unique elements first, then makes found array unique with the use of Set.

    So we have array of duplicates in the end.

    var array = [1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 7, 8, 5, 22, 1, 2, 511, 12, 50, 22];
    
    console.log([...new Set(
      array.filter((value, index, self) => self.indexOf(value) !== index))]
    );

提交回复
热议问题