我试图创建一个函数,它给出了一个数字数组,每个数字都有重复限制。例如
([1,1,3,3,7,2,2,2,2], 3)
应该给我
[1, 1, 3, 3, 7, 2, 2, 2]
它删除了[2],因为数字的最大重复次数是3。
这是我的代码,但我不知道它为什么不起作用:
function deleteNth(arr,n){
var results = [];
for(var i=0; i<arr.length; i++){
if (count(results, arr[i])<=n) {
results.push(arr[i]);
}
}
return results;
}
function count(array, what){
var count =0;
for (var i=0; i<array.length; i++){
if (array[i]===what){
count++;
}
}
return count;
}
console.log(deleteNth([1,1,3,3,7,2,2,2,2], 3));
答案 0 :(得分:3)
我也发现了这个:
function deleteNth(arr,x) {
var cache = {};
return arr.filter(function(n) {
cache[n] = (cache[n]||0) + 1;
return cache[n] <= x;
});
}
答案 1 :(得分:0)
我会使用reduce
迭代数组的所有元素和字典来跟踪我找到元素的次数。
以下是一个例子:
const filterReps = (arr, maxReps) => {
return arr.length ? arr.reduce((acc, num, i) => {
// Add this number to our dictionary,
// if already present add +1 to it's count
acc.found[num] = acc.found[num] ? ++acc.found[num] : 1
// If the dictionary says the number has been found less or equal
// times to our max repetitions, push it into the accumulating array
if (acc.found[num] <= maxReps)
acc.arr.push(num)
// If this is the final iteration, just return only the result array
// and not the dictionary
return i === nums.length - 1 ? acc.arr : acc
}, { found: {}, arr: [] }) : arr
}
const nums = [1, 1, 1, 1, 2, 2, 2, 2]
console.log(filterReps(nums, 3))
答案 2 :(得分:0)
通过仅使用一个函数,您可以使这更简单一些。以下是如何完成的示例:
function dn(arr,n){
results = {};
for(var i=0; i<arr.length; i++){
if(!results[arr[i]]){
results[arr[i]] = 1;
}else if(results[arr[i]] + 1 <= n){
results[arr[i]]++
}
}
data = []
Object.keys(results).forEach(function(key){
for(i=0; i<results[key]; i++){
data.push(key);
}
});
return data;
}
答案 3 :(得分:0)
试试这个,我想这对你也有帮助。
function removeMoreDups(your_array, limit) {
new_arr = [];
var counts = {};
your_array.forEach(function(x) {
counts[x] = (counts[x] || 0)+1;
if (counts[x] <= limit) {
new_arr.push(x);
}
});
return new_arr;
}
your_array = [1,1,3,3,7,2,2,2,2];
limit = 3;
new_arr = removeMoreDups(your_array, limit);
console.log(new_arr);
答案 4 :(得分:0)
var itemCounter = ((char, tab) => tab.filter((tabItem) => (tabItem === char)).length);
function deleteNth(arr,n){
var tempTab = [];
arr.forEach((item) => {
if(itemCounter(item,tempTab) < n)
tempTab.push(item);
});
return tempTab;
}