niisar
1/2/2017 - 9:52 AM

find duplicate in JavaScript

find duplicate in JavaScript

//this prototype function checks if an element is already in the array or not
//go through all the array and push the element to result if it is not 
//this way we can eliminate duplicates 
//result will contain the resultant array
Array.prototype.contains = function(k) {
  for ( var p in this)
    if (this[p] === k)
      return true;
  return false;
};

function findDuplicates(Numbers) {
  var arrayLength = Numbers.length, i, j, result = [];
  for (i = 0; i < arrayLength; i++) {
    for (j = 0; j < arrayLength; j++) {
      if (a[i] == a[j] && i != j && !result.contains(a[i])) {
        result.push(a[i]);
      }
    }
  }
  return result;
}