1

I need to write a function to find all the elements that appear more than once in the array and then return those elements in an array. Example: Input: [2,7,4,10,12,27,4,7,7,12, 10] Output: [4,7,10,12]

This is what i have so far:

let arr= [4,4,6,8,8,9,10,10]

var method1 = function(a) {
  var counts = [];
    for(var i = 0; i <= a.length; i++) {
        for(var j = i; j <= a.length; j++) {
            if(i != j && a[i] == a[j]) {
                counts.push(a[i]);
                }
              }
            }

    return counts;
}
console.log(method1(arr));

It works when the array only have two of a number, but not if there are more. How can I push to counts only one of each number independently of how many duplicates there are?

thanks for any help!

  • Possible duplicate of [Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array](https://stackoverflow.com/questions/840781/get-all-non-unique-values-i-e-duplicate-more-than-one-occurrence-in-an-array) – Forketyfork Mar 02 '19 at 19:01

4 Answers4

2

You could take a hash table for counting the values and if you have a count of two, take this element.

var array = [2, 7, 4, 10, 12, 27, 4, 7, 7, 12, 10],
    hash = Object.create(null),
    result = array.filter(v => (hash[v] = (hash[v] || 0) + 1) === 2);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You use Array.prototype.filter() and compare indexOf() and lastIndexOf() of element to check if occurs more than once

const method1 = (arr) => [...new Set(arr.filter(elm => arr.indexOf(elm) !== arr.lastIndexOf(elm)))]
console.log(method1([2,7,4,10,12,27,4,7,7,12, 10]))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

Use a marker that would signal that item was already seen. It can be done with a dictionary

let arr= [4,4,6,8,8,9,10,10];

function solution(arr) {
  const marker = {};
  const duplicates = []
  for (const item of arr) {
    if (marker[item]) {
      duplicates.push(item);
    } else {
      marker[item] = true;
    }
  }
  return duplicates;
}

const s = solution(arr);
console.log(s);
marzelin
  • 10,790
  • 2
  • 30
  • 49
0

You can use reduce

Here the idea is :-

  • We initialize op with two keys unique and repeated.
  • whenever any digit appear for the first time we initialize unique with that digit as key value pair. now when the same digit appear again we set repeated property with that digit as key value pair.
  • In the end we take values out of repeated key

let arr = [2,7,4,10,12,27,4,7,7,12, 10]

let op = arr.reduce((op, inp) => {
  if(op.unique[inp] !== undefined){
    op.repeated[inp] = inp
  } else{
    op.unique[inp] = inp
  }
  return op
},{unique:{},repeated:{}})

console.log(Object.values(op.repeated))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60