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

后端 未结 30 3159
再見小時候
再見小時候 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:22

    Here's the simplest solution I could think of:

        const arr = [-1, 2, 2, 2, 0, 0, 0, 500, -1, 'a', 'a', 'a']
    
        const filtered = arr.filter((el, index) => arr.indexOf(el) !== index)
        // => filtered = [ 2, 2, 0, 0, -1, 'a', 'a' ]
    
        const duplicates = [...new Set(filtered)]
    
        console.log(duplicates)
        // => [ 2, 0, -1, 'a' ]
    

    That's it.

    Note:

    1. It works with any numbers including 0, strings and negative numbers e.g. -1 - Related question: Get all unique values in a JavaScript array (remove duplicates)

    2. The original array arr is preserved (filter returns the new array instead of modifying the original)

    3. The filtered array contains all duplicates; it can also contain more than 1 same value (e.g. our filtered array here is [ 2, 2, 0, 0, -1, 'a', 'a' ])

    4. If you want to get only values that are duplicated (you don't want to have multiple duplicates with the same value) you can use [...new Set(filtered)] (ES6 has an object Set which can store only unique values)

    Hope this helps.

提交回复
热议问题