[JavaScript] Find duplicate elements

Title description

Find the repeated elements in the array arr
Example 1

Enter
[1, 2, 4, 4, 3, 3, 1, 5, 3]

Output
[1, 3, 4]
solution:

function duplicates(arr) {
    
    
    var num=arr.sort();
    var xx=[];
    var i;
    for(i=0;i<arr.length;i++){
    
    
            if(arr[i]==arr[i+1]&&arr[i]!=arr[i-1])//判断是否重复,是否已经放入容器
            {
    
    
                xx.push(arr[i]);
            }
        }
    return  xx;   
}

I saw another clever solution, which is similar to the above solution, but the judgment sentence is different:


function duplicates(arr) {
    
    
 var result = [];
    arr.forEach(function(elem){
    
    
       if(arr.indexOf(elem) !=arr.lastIndexOf(elem) && result.indexOf(elem) == -1){
    
    
           result.push(elem);
       }
    });
    return result;
}

Among them, result.indexOf(elem) == -1 I didn't understand it at first, and then I thought about it, hurt! Isn’t it just to avoid duplication of data in the new array?

Guess you like

Origin blog.csdn.net/weixin_42345596/article/details/104925427