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

前端 未结 5 972
谎友^
谎友^ 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:21

    This should do the trick:

    Array.prototype.getUnique = function(){
        var uniques = [];
        for(var i = 0, l = this.length; i < l; ++i){
            if(this.lastIndexOf(this[i]) == this.indexOf(this[i])) {
                uniques.push(this[i]);
            }
        }
        return uniques;
    }
    
    // Usage:
    
    var a = [2, 6, 7856, 24, 6, 24];
    alert(JSON.stringify(a.getUnique()));
    
    console.log(a.getUnique()); // [2, 7856]

    To check if a specific item is unique in the array, it just checks if the first index it's found at, matches the last index it's found at.

    0 讨论(0)
  • 2020-12-02 01:29

    When it comes to removing duplicates from an array I usually use one approach:

    const arrWithDuplicates = [1,2,2,2,3,4,4]
    const arrWithUniqueValues = [...new Set(arrWithDuplicates)]
    
    // result will be: [1,2,3,4]
    

    This also works with strings and booleans.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-02 01:42

    The other answers so far all have O(n log n) time complexity or worse. This can be done in O(n) time though the use of Sets (Set.has has O(1) complexity) instead of nested loops:

    // .sort has complexity O(n log n): it's not needed here, avoid it
    const getOnlyUniques = (arr) => {
      const foundOnce = new Set();
      const foundTwice = new Set();
      arr.forEach((item) => {
        if (foundOnce.has(item)) {
          foundTwice.add(item);
        }
        foundOnce.add(item);
      });
      return arr.filter(item => !foundTwice.has(item));
    };
    console.log(getOnlyUniques([2, 3, 2]));

    0 讨论(0)
  • 2020-12-02 01:47

    One alternative with filter() function:

    var myArray = [1,2,3,2,2,4,3,7,3].sort();
    var uniqueValues = myArray.filter(function(item, i, arr) {
      return (item !== arr[i-1] && item !== arr[i+1]);
    });
    

    Where uniqueValues = [1,4,7]

    0 讨论(0)
提交回复
热议问题