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

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

    UPDATED: Short one-liner to get the duplicates:

    [1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i) // [2, 4]
    

    To get the array without duplicates simply invert the condition:

    [1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) === i) // [1, 2, 3, 4]
    

    I simply did not think about filter() in my old answer below ;)


    When all you need is to check that there are no duplicates as asked in this question you can use the every() method:

    [1, 2, 3].every((e, i, a) => a.indexOf(e) === i) // true
    
    [1, 2, 1].every((e, i, a) => a.indexOf(e) === i) // false
    

    Note that every() doesn't work for IE 8 and below.

提交回复
热议问题