How to write an array deduplication method?

A relatively simple implementation is:

1. Create an empty array first to save the final result
2. Loop each element in the original array
3. Perform a second loop on each element to determine whether there is the same element. If not, put this element in the new array
4. Return this new array
<script>
    var arr = [1,2,"2","4",5,2,1];
 
    var newArr = removeRepetition(arr);
    console.log(newArr);
 
    function removeRepetition(arr){
    
    
        var newArr = [];
        //typeof (arr) == "string"?newArr = "":newArr = [];
        if (newArr.length == 0) {
    
    
            newArr.push(arr[0]);
        }
        if (newArr.length != 0) {
    
    
            for (var i in arr) {
    
    
                if (newArr.indexOf(arr[i]) == -1) {
    
    
                    newArr.push(arr[i]);
                }
            }
        }
        if(typeof arr == "object"){
    
    
            return newArr;
        }
        if(typeof arr == "string"){
    
    
            var arrStr = "";
            for(var i=0;i<newArr.length;i++){
    
    
                arrStr += newArr[i];
            }
            return arrStr;
        }
    }
 
</script>

Guess you like

Origin blog.csdn.net/ni15534789894/article/details/111594667