gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:45:01 29 4
gpt4 key购买 nike

你好,我要取一个整数数组,数字范围从 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]);

最佳答案

如果我没理解错的话,你可以通过 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)` )
}

关于javascript - 如何使用javascript查找和计算数组中的重复整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55527452/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com