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

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

    I have just figured out a simple way to achieve this using an Array filter

        var list = [9, 9, 111, 2, 3, 4, 4, 5, 7];
        
        // Filter 1: to find all duplicates elements
        var duplicates = list.filter(function(value,index,self) {
           return self.indexOf(value) !== self.lastIndexOf(value) && self.indexOf(value) === index;
        });
        
        console.log(duplicates);

提交回复
热议问题