2

I have an array [1,1,1,1,2,3,4,5,5,6,7,8,8,8]

How can I get an array of the distinct duplicates [1,5,8] - each duplicate in the result only once, regardless of how many times it appears in the original array

my code:

var types = availControls.map(item => item.type);
var sorted_types = types.slice().sort();

availControlTypes = [];
for (var i = 0; i < sorted_types.length - 1, i++) {
   if (sorted_types[i + 1] == sorted_types[i])
   availControlTypes.push(sorted_types[i]);
}

This gets me the duplicates, but not unique.

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
full-stack
  • 553
  • 5
  • 20

4 Answers4

1

You need a for loop, with an object that will hold the number of times the number appeared in the array. When the count is already 1, we can add the item to the result. We should continue to increment the counter, so we won't add more than a single duplicate of the same number (although we can stop at 2).

function fn(arr) {
  var counts = {};
  var result = [];
  var n;
  
  for(var i = 0; i < arr.length; i++) {
    n = arr[i]; // get the current number
    
    if(counts[n] === 1) result.push(n); // if counts is exactly 1, we should add the number to results
    
    counts[n] = (counts[n] || 0) +1; // increment the counter
  }
  
  return result;
}

var arr = [1, 1, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8];

var result = fn(arr);

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

This will do it

var input = [1, 1, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8];

let filterDuplicates = arr => [...new Set(arr.filter((item, index) => arr.indexOf(item) != index))]


console.log(filterDuplicates(input)) 
Mike Ezzati
  • 2,968
  • 1
  • 23
  • 34
0

ES6 1 liner. This is very similar to how we find unique values, except instead of filtering for 1st occurrences, we're filtering for 2nd occurrences.

let nthOccurrences = (a, n = 1) => a.filter((v, i) => a.filter((vv, ii) => vv === v && ii <= i).length === n);

let x = [1, 1, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8];

let uniques = nthOccurrences(x, 1);
let uniqueDuplicates = nthOccurrences(x, 2);
let uniqueTriplets = nthOccurrences(x, 3); // unique values with 3 or more occurrences

console.log(JSON.stringify(uniques));
console.log(JSON.stringify(uniqueDuplicates));
console.log(JSON.stringify(uniqueTriplets));
junvar
  • 11,151
  • 2
  • 30
  • 46
0
const dupes = arr =>
  Array.from(
    arr.reduce((acc, item) => {
      acc.set(item, (acc.get(item) || 0) + 1);
      return acc;
    }, new Map())
  )
    .filter(x => x[1] > 1)
    .map(x => x[0]);

const arr = [1, 1, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8];

console.log(dupes(arr));

// [ 1, 5, 8 ]
Hero Qu
  • 911
  • 9
  • 10