DTR9000
DTR9000

Reputation: 179

How to keep Duplicates of an Array

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.

Upvotes: 7

Views: 6948

Answers (4)

bangash
bangash

Reputation: 408

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.

Upvotes: 2

jjones150
jjones150

Reputation: 302

Here is my procedural solution:

var arr = [1,1,2,3,3,3,3,4,5,5]
var arr2 =[];
        for(var i=0; i < (arr.length-1); i++){
                    if (arr2.indexOf(arr[i]) > -1 || arr[i] != arr[i+1]){                       
                        //Do Nothing and move on to the next set
                    }
                    else{
                        arr2.push(arr[i]);                  
                    }
        }   

Upvotes: 0

Hassan Imam
Hassan Imam

Reputation: 22534

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; }

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

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);

Upvotes: 13

Related Questions