2

Hello I am taking an array of integers with ranging numbers from 1 - 100 and I'm counting the duplicated numbers within it. Example, array[1,1,1,1,1,100,3,5,2,5,2,23,23,23,23,23,]. Result = 1 - 5 times, 5 - 2 times, 2 - 2 times, 23 - 5 times. I cannot see how to make this work I have tried to edit this code snippet so that it counts and returns the number of duplicates of a specific integer that is a duplicate but I could not see how to do it. Please assist Thank You.

https://repl.it/@youngmaid/JS-ALGORITHMS-Counting-Duplicates

//To count or reveal duplicates within an array. Using the array method of sort() is one way.
//Sort the following array using .sort(), which put the items in the array in numerical or alphabetical order.
//Create a new variable for the sorted array.
//Also create a new variable for an empty array.
//Create a loop using the length of the first, original array with an increment of "++".
//Create an if statement that includes adding an item comparing to the index. 
//Then push the emply array in the sorted array.
//console log the new array.



let duplicateArr = [5, 3, 7, 4, 7, 5, 3, 2, 7, 3, 2];
let sortArr = duplicateArr.sort();

let newArr = [];
for(let i = 0; i < duplicateArr.length; i++) {
  if(sortArr[i + 1] == sortArr[i]){
    newArr.push(sortArr[i]);
  }
}
  console.log(newArr);

//The other way or more detailed/reusable approach is to create a function and variable hash table. 
//The hash table to place all the items in the array. 
//Then create another variable placing duplicates in the array.
//Then go through each item in the array through a for loop. (Using arr as the argument).
//Create a conditional if/else statement.  If the item in the hash table does not exist, then insert it as a duplicate.


function duplicates(arr) {
   let hashTable = [];
   let dups = [];
   for (var i = 0; i < arr.length; i++){
     if (hashTable[arr[i].toString()] === undefined) {
       hashTable[arr[i].toString()] = true;
     } else {
        dups.push(arr[i]);
     }
   }
   return dups;
}

duplicates([3, 24, -3, 103, 28, 3, 1, 28, 24]);
Roboman Robo
  • 599
  • 2
  • 5
  • 16

6 Answers6

1

If I understand correctly, you could achieve this via Array#reduce() as shown below:

let duplicateArr = [5, 3, 7, 4, 7, 5, 3, 2, 7, 3, 2];

/* Reduce the input duplicateArr to a map relating values to counts */
const valueCounts = duplicateArr.reduce((counts, value) => {
  
  /* Determine the count of current value from the counts dictionary */
  const valueCount = (counts[ value ] === undefined ? 0 : counts[ value ])
  
  /* Increment count for this value in the counts dictionary */
  return { ...counts, ...{ [value] : valueCount + 1 } }
  
}, {})

/* Remove values with count of 1 (or less) */
for(const value in valueCounts) {
  if(valueCounts[value] < 2) {
    delete valueCounts[value]
  }
}

/* Display the values and counts */
for(const value in valueCounts) {
  console.log(`${ value } occours ${ valueCounts[value] } time(s)` )
}
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
1

Reasonably basic loop approach

const data = [1, 1, 1, 1, 1, 100, 3, 5, 2, 5, 2, 23, 23, 23, 23, 23, ]

function dupCounts(arr) {
  var counts = {};
  arr.forEach(function(n) {
   // if property counts[n] doesn't exist, create it
    counts[n] = counts[n] || 0;
    // now increment it
    counts[n]++;
  });
  
  // iterate counts object and remove any that aren't dups
  for (var key in counts) {
    if (counts[key] < 2) {
      delete counts[key];
    }
  }

  return counts
}

console.log(dupCounts(data))
charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

You can just iterate over all of the unique values and then count how many of them exists.

here is a sample code:

let duplicateArr = [5, 3, 7, 4, 7, 5, 3, 2, 7, 3, 2];
let sortArr = duplicateArr.sort();
let newArr = {};
let duplicateValues = [];
for (let i = 0; i < duplicateArr.length; i++) {
  let count = 0;
  let k = 0;
  while (i + k < duplicateArr.length && sortArr[i] == sortArr[i + k]) {
    count++;
    k++;
  }
  if (count > 1) {
    newArr[sortArr[i]] = count;
    duplicateValues.push(sortArr[i]);
  }
  i = i + k;
}

console.log("duplicate items with count:", newArr);
console.log("duplicate items:", duplicateValues);
MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37
1

Here using only 1 loop.

let duplicateArr = [5, 3, 7, 4, 7, 5, 3, 2, 7, 3, 2]
let sortArr = duplicateArr.sort()
let current = 0, counter = 0
sortArr.forEach(n => {
  if (current === n) {
    counter++
  }
  else  {
    if (counter > 1){
      console.log(current + " occurs " + counter + " times.")
    }
    counter = 1
    current = n
  }
})
if (counter > 1){
  console.log(current + " occurs " + counter + " times.")
}
holydragon
  • 6,158
  • 6
  • 39
  • 62
1

Using Array.prototype.reduce() you can create a hash object variable containing as keys the numbers in the duplicateArr array variable and the values are the number of repeated times..

Code:

const duplicateArr1 = [5, 3, 7, 4, 7, 5, 3, 2, 7, 3, 2];
const duplicateArr2 = [1, 1, 1, 1, 1, 100, 3, 5, 2, 5, 2, 23, 23, 23, 23, 23];

const getStringOfDuplicated = array => {
  const hash = array.reduce((a, c) => (a[c] = ++a[c] || 1, a), {});
  return Object.entries(hash)
    .filter(([k, v]) => v > 1)
    .sort(([ak, av], [bk, bv]) => bv - av)
    .map(([k, v]) => `${k} - ${v} times`)
    .join(', ');
};


console.log(getStringOfDuplicated(duplicateArr1));
console.log(getStringOfDuplicated(duplicateArr2));
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
  • 1
    @TylerRoper, Improved the answer to get the proper formatted string as result.. Thanks for your comment – Yosvel Quintero Apr 05 '19 at 03:26
  • Can you please sort by the greatest occurring duplicates to the least occurring duplicates? Liking this solution. I would like to be able to use the int the count of the duplicates of number, for calculations so it would be better if that were possible ( Don't see how to get the ints) . Also if there was a new line added so that each result shows up on a new line in the console that would be great. Comments would also be great, Thank You. – Roboman Robo Apr 05 '19 at 08:58
  • 1
    @RobomanRobo Sure, I have added sorting by the greatest occurring duplicates – Yosvel Quintero Apr 05 '19 at 10:00
  • Thanks @YosvelQuintero . I ran the code and it works. (your snip isn't working by the way with your update just so you know but its fine for me) The last thing I'm trying to do is just get it to show up on a new line in the console. I have tryed replacing .join with .join('/n'); but will not work thanks, you are appreciated. – Roboman Robo Apr 05 '19 at 11:03
  • @RobomanRobo I checked and is working.. Was added the sorting by the greatest occurring duplicates – Yosvel Quintero Apr 06 '19 at 09:23
  • Thanks. I know in my last message, it says "last thing I'm trying to do is just get it to show up on a new line in the console". That is it and it is done. – Roboman Robo Apr 06 '19 at 12:51
1

The cleanest way is using ES6 Map

function duplicates(arr) {
    // This will be the resulting map
    const resultMap = new Map();
    // This will store the unique array values (to detect duplicates using indexOf)
    const occurrences = [];

    for (let i of arr){
        if (occurrences.indexOf(i) !== -1) {
            // Element has a duplicate in the array, add it to resultMap
            if (resultMap.has(i)) {
                // Element is already in the resultMap, increase the occurrence by 1
                resultMap.set(i, resultMap.get(i) + 1);
            } else {
                // Element is not in resultMap, set its key to 2 (the first 2 occurrences)
                resultMap.set(i, 2);
            }
        } else {
            // Element is showing for the first time (not a duplicate yet)
            occurrences.push(i);
        }
    }
    return resultMap;
}

// To iterate on the map keys and values use this
for (const [key, value] of map) {
    console.log(key + ' - ' + value + ' times');
}
Ali Elkhateeb
  • 3,413
  • 4
  • 21
  • 39