简体   繁体   中英

Get distinct duplicates from array

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.

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)

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

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

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 ]

Looks like I'm a little late but here's an answer using index values instead of counting:

 function parse(arr) { var result = []; for (var i = 0; i < arr.length; i++) { if (arr.indexOf(arr[i]) === i){ result.push(arr[i]) } } return result; } var filtered = parse([1, 1, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8]) console.log(filtered)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM