5

I have to get a list of values that exist more than once in an array. This is current code , but as you can see it's too complicated.

var arr = [1, 2, 3, 4, 2, 3];
var flag = {}
var exist2arr = [];

for(var i = 0; i < arr.length; i++){
  for(var j = 0 ; j < arr.length; j ++){
     if(i !=j && arr[i] == arr[j]){
       if(!flag[arr[i]])
         exist2arr.push(arr[i]);
       flag[arr[i]] = 1;
     }
  }
}
console.log(exist2arr);

Is there any other way (simple code using javascript built-in function) to achieve this? Any kind of help appreciate.

HerrGanzorig
  • 51
  • 1
  • 14
  • If by "exist more than twice" you mean "exist more than once", then you can start with something like `for (var i = 0; i < arr.length; i++) { if (arr.indexOf(arr[i]) !== i) { }}` – Hamms Nov 15 '17 at 02:42
  • Sorry for poor english, i mean `>1` – HerrGanzorig Nov 15 '17 at 02:43
  • @Hamms, don't forget that indexOf() could return -1, which would also not equal the current array index. –  Nov 15 '17 at 02:59
  • @codemaker it's pretty safe to assume that `arr.indexOf(arr[0 <= i < arr.length])` will always be >= 0 – Phil Nov 15 '17 at 03:00
  • Oops, my bad @Hamm...overlooked that part. sorry. –  Nov 15 '17 at 03:02

4 Answers4

6

You could filter the array based on values who's first and current indexes are not equal then run that array through a Set

const arr = [1, 2, 3, 4, 2, 3, 2, 3, 2, 3, 2, 3]; // added in some extras

const filtered = arr.filter((v, i) => arr.indexOf(v) !== i)
const unique = new Set(filtered)

console.info(Array.from(unique)) // using Array.from so it can be logged
Phil
  • 157,677
  • 23
  • 242
  • 245
4

var arr = [1, 2, 3, 4, 2, 3];

var o = arr.reduce((o, n) => {
  n in o ? o[n] += 1 : o[n] = 1;
  return o;
}, {});

var res = Object.keys(o).filter(k => o[k] > 1);

console.log(res);
2

A bit hacky, but short and O(n):

var arr = [1, 2, 3, 4, 2, 3, 2, 2]

var a = arr.reduce((r, v) => ((r[v + .1] = r[v + .1] + 1 || 1) - 2 || r.push(v), r), [])

console.log( a )              // [2,3]
console.log({ ...a })         // to show the "hidden" items
console.log({ ...a.slice() }) // .slice() can be used to remove the extra items
Slai
  • 22,144
  • 5
  • 45
  • 53
0

It could be done like:

function timesInArray(v, a){
  var n = 0;
  for(var i=0,l=a.length; i<l; i++){
    if(a[i] === v){
      n++;
    }
  }
  return n;
}
function dups(dupArray, num){
  var n = num === undefined ? 2 : num;
  var r = [];
  for(var i=0,d,l=dupArray.length; i<l; i++){
    d = dupArray[i];
    if(!timesInArray(d, r) && timesInArray(d, dupArray) >= n){
      r.push(d);
    }
  }
  return r;
}
var testArray = [4, 5, 2, 5, 7, 7, 2, 1, 3, 7, 7, 7, 25, 77, 4, 2];
console.log(dups(testArray)); console.log(dups(testArray, 3));
StackSlave
  • 10,613
  • 2
  • 18
  • 35