Javascript remove all occurrence of duplicate element, leaving the only one that is unique

前端 未结 5 986
谎友^
谎友^ 2020-12-02 01:20

I want to remove elements that occurr more than once and get the unique element. The array always has 3 elements. Lets say i have an array [2,3,2], then I need to get 3 whi

5条回答
  •  余生分开走
    2020-12-02 01:40

    An alternative:

    var a = [2,3,2], result = [];
    
    for(var i = 0; i < a.length; i++){
    
        if(getAllIndexes(a, a[i]).length === 1)
            result.push(a[i]);
    }
    
    console.log(result);
    
    function getAllIndexes(arr, val) {
        var indexes = [], i = -1;
        while (~(i = arr.indexOf(val, i+1)))
            indexes.push(i);
        return indexes;
    }
    

提交回复
热议问题