How to keep Duplicates of an Array

Viewed 4913

In Javascript, I'm trying to only keep Duplicates in an Array.

For Example my initial Array is

[1,1,2,3,3,3,3,4,5,5]

the Result should be

[1,3,5]

I've tried working with .indexOf() and $.inArray(), but can't figure it out. I know how to remove Duplicates, but to keep them is quite difficult.

4 Answers

You could filter by checking if the item is the first one and if the last index is not the actual index.

var array = [1, 1, 2, 3, 3, 3, 3, 4, 5, 5],
    result = array.filter((a, i, aa) => aa.indexOf(a) === i && aa.lastIndexOf(a) !== i);

console.log(result);

All of the above using O(n2) which is expansive, if you want to achieve O(n) time so here is the solution.

function getDuplicates(arr){
  const hashTable = {} 
  const duplicate = [];
  arr.forEach((item) => {
    if(hashTable[item]){
      if(hashTable[item] === 1){
         duplicate.push(item);
      }
     hashTable[item] = hashTable[item] + 1;
    } else {
      hashTable[item] =1;
    }
  })

  return duplicate;
}

I also write the article to how effectively remove duplication from the array by using a javascript object like a hashtable.

You can use array#reduce to count the frequency of each value and then array#filter values whose count is greater than 1.

var data = [1,1,2,3,3,3,3,4,5,5];
var count = data.reduce((o,v)=>{
  o[v] = o[v]+1 || 1;
  return o;
},{});

var duplicate = Object
                  .keys(count)
                  .filter(k => count[k] > 1)
                  .map(Number);
console.log(duplicate);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Another version of solution using Map.

var data = [1,1,2,3,3,3,3,4,5,5];
var count = data.reduce((map,v)=>{
  map.set(v, (map.get(v) || 0) + 1);
  return map;
},new Map());

var duplicate = Array.from(count)
                     .filter(a => a[1] > 1)
                     .map(a => a[0]);
console.log(duplicate);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related