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

后端 未结 30 3165
再見小時候
再見小時候 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条回答
  •  既然无缘
    2020-11-21 05:36

    This is my proposal (ES6):

    let a = [1, 2, 3, 4, 2, 2, 4, 1, 5, 6]
    let b = [...new Set(a.sort().filter((o, i) => o !== undefined && a[i + 1] !== undefined && o === a[i + 1]))]
    
    // b is now [1, 2, 4]
    

提交回复
热议问题