How to remove duplicate entries from an array while maintaining inconsistent duplicates?

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

  • Go through all the elements one by one.
  • If the element matches the prev element, count the element and do something like newA = arr.slice(i, count)
  • The new array should be filled only with identical elements.
  • In my input example, the first 3 elements are identical, so it newAwill be like arr.slice(0, 3), and it newBwill be arr.slice(3,5), etc.

I tried turning this into the following code:

function identical(array){
    var count = 0;
    for(var i = 0; i < array.length -1; i++){
        if(array[i] == array[i + 1]){
            count++;
            // temp = array.slice(i)
        }else{
            count == 0;
        }
    }
    console.log(count);
}
identical(arr);

, , , . , , .

+4
5

array.filter(), , .

- :

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>
Hide result
+13

-

var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];

    function identical(array){

        var newArray=[];
        newArray.push(arr[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;

+4

, , , .

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

[5,2,9,4,5]

, , , , .

+1

: 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>
Hide result
+1

:

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
source

All Articles