如何使用JavaScript查找和计算数组中的重复整数

时间:2019-04-05 02:31:18

标签: javascript

你好,我正在获取一个整数数组,其整数范围为1-100,我正在计算其中的重复数字。例如,数组[1,1,1,1,1,100,3,5,2,5,2,23,23,23,23,23,]。结果= 1-5次,5-2次,2-2次,23-5次。我看不到如何进行此工作,我尝试编辑此代码段,以便计算并返回作为重复项的特定整数的重复项数量,但我看不到如何做。请协助谢谢。

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

6 个答案:

答案 0 :(得分:1)

如果我的理解正确,您可以通过Array#reduce()实现此目标,如下所示:

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

答案 1 :(得分:1)

合理的基本循环方法

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

答案 2 :(得分:1)

您可以仅遍历所有唯一值,然后计算其中存在多少个唯一值。

下面是示例代码:

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

答案 3 :(得分:1)

这里仅使用1个循环。

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

答案 4 :(得分:1)

使用Array.prototype.reduce(),您可以创建一个hash对象变量,其中包含key数组变量中的数字作为duplicateArr,而values是重复几次。

代码:

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

答案 5 :(得分:1)

最干净的方法是使用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');
}