How to remove repeated entries from an array while preserving non-consecutive duplicates?

前端 未结 5 1914
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 19:35

I have an array like var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5]; I really want the output to be [5,2,9,4,5]. My logic for this was:

相关标签:
5条回答
  • 2020-12-06 19:38

    if you are looking purely by algorithm without using any function

    var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
    
        function identical(array){
    
            var newArray = [];
            newArray.push(array[0]);
            for(var i = 0; i < array.length -1; i++) {
                if(array[i] != array[i + 1]) {
                    newArray.push(array[i + 1]);
                }
            }
            console.log(newArray);
        }
        identical(arr);
    

    Fiddle;

    0 讨论(0)
  • 2020-12-06 19:40

    A bit hackey, but, hell, I like it.

    var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
    var arr2 = arr.join().replace(/(.),(?=\1)/g, '').split(',');
    

    Gives you

    [5,2,9,4,5]
    

    Admittedly this will fall down if you're using sub-strings of more than one character, but as long as that's not the case, this should work fine.

    0 讨论(0)
  • 2020-12-06 19:55

    Try this:

    var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
    
    uniqueArray = a.filter(function(item, pos) {
    return a.indexOf(item) == pos;
    });
    

    See Remove Duplicates from JavaScript Array

    0 讨论(0)
  • 2020-12-06 19:59

    Using array.filter() you can check if each element is the same as the one before it.

    Something like this:

    var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
    
    var b = a.filter(function(item, pos, arr){
      // Always keep the 0th element as there is nothing before it
      // Then check if each element is different than the one before it
      return pos === 0 || item !== arr[pos-1];
    });
    
    document.getElementById('result').innerHTML = b.join(', ');
    <p id="result"></p>

    0 讨论(0)
  • 2020-12-06 19:59

    Yet another way with reduce

    var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
    
    var result = arr.reduce(function(acc, cur) {
      if (acc.prev !== cur) {
        acc.result.push(cur);
        acc.prev = cur;
      }
      return acc;
    }, {
      result: []
    }).result;
    
    
    document.getElementById('d').innerHTML = JSON.stringify(result);
    <div id="d"></div>

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