admin管理员组

文章数量:1355555

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.

/@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 paring 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]);

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 paring 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]);
Share Improve this question asked Apr 5, 2019 at 2:31 Roboman RoboRoboman Robo 6892 gold badges8 silver badges20 bronze badges 3
  • do u want to print count of all repeating elements? – vinayak shahdeo Commented Apr 5, 2019 at 2:42
  • Possible duplicate of How to count duplicate value in an array in javascript – Ali Elkhateeb Commented Apr 5, 2019 at 3:07
  • @vinayak_shahdeo Yes. – Roboman Robo Commented Apr 5, 2019 at 7:44
Add a ment  | 

6 Answers 6

Reset to default 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)` )
}

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

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.")
}

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

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

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

本文标签: How to find and count duplicate integers in an array with javascriptStack Overflow