This code is not very understood, please help to popularize science.

this code is not very understood, ask the great god for help under the popular science. The main reason is that the code in the 2 for loops is a little unintelligible, so if it is convenient to add comments to explain it.

     var array =  ["c", "a", "z", "a", "x", "a"];
            function clear() {
                var o = {};//
                for(var i = 0; i < array.length; iPP) {
                    var item = array[i];//
                    if(o[item]) {
                        o[item]PP;
                    } else {
                        o[item] = 1;
                    }
                }//end for
                var tmpArray = [];
                for(var key in o) {
                    if(o[key] == 1) {
                        tmpArray.push(key);
                    } else {
                        if(tmpArray.indexOf(key) == -1) {
                            tmpArray.push(key);
                        }
                    }
                }//end for
                return tmpArray;
            }//end function
            
            console.log(clear(array));
Mar.22,2021

@ shoyuf the answer is right. This code does the array deduplication through the uniqueness of the Object key value, but this method is only effective for the string array, because in the end it takes the object's key value push into the tmpArray, and the object's key value is of string type. If the array that needs to be deduplicated is [1, 1, 4, 8, 10, 8], the final result according to this method is ['1','4','8','10'], which changes the type of data, so it is not recommended when you do not know the type of the specific data of the array.
recommends a simple way to remove duplicates from arrays:


!

set

var newArr = [...new Set(array)];

it's also very simple if you want to implement it yourself

var array =  ['c', 'a', 'z', 'a', 'x', 'a'];
function distinct(arr) {
    const ret = {}
    arr.forEach(item => ret[item] = true);
    return Object.keys(ret)
}
distinct(array) // ['c', 'a', 'z', 'x']
Menu