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

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

提交回复
热议问题