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

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

    The following function (a variation of the eliminateDuplicates function already mentioned) seems to do the trick, returning test2,1,7,5 for the input ["test", "test2", "test2", 1, 1, 1, 2, 3, 4, 5, 6, 7, 7, 10, 22, 43, 1, 5, 8]

    Note that the problem is stranger in JavaScript than in most other languages, because a JavaScript array can hold just about anything. Note that solutions that use sorting might need to provide an appropriate sorting function--I haven't tried that route yet.

    This particular implementation works for (at least) strings and numbers.

    function findDuplicates(arr) {
        var i,
            len=arr.length,
            out=[],
            obj={};
    
        for (i=0;i

提交回复
热议问题