我应该以更简单的方式询问,而不是展示我一直想做的事情。 假设我有这个数组:
function scr(array, n){
}
scr([187,187,187,187,187,62,62,43,43,43,43,43,5,5,5], 5)
我想得到一个数组,显示出现一定次数的数字。在这种情况下,我希望出现5次的数字,然后给出:
[187,43]
我该怎么办?
PS:对于复杂的上一个问题抱歉
答案 0 :(得分:2)
您可以使用reduce
对数组中的项目进行分组,为每个数字计算一个数字,然后按计数为5的数字对其进行过滤:
const input = [187,187,187,187,187,62,62,43,43,43,43,43,5,5,5];
const count = input.reduce((a, num) => {
a[num] = (a[num] || 0) + 1;
return a;
}, {});
const fives = Object.entries(count)
.filter(([, occurrences]) => occurrences === 5)
.map(([num]) => Number(num));
console.log(fives);
答案 1 :(得分:1)
不是性能最高但可读性最强,它是减少
的好地方https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
const numbers = [187, 187, 187, 187, 187, 62, 62, 43, 43, 43, 43, 43, 5, 5, 5];
function equalFive(array, num) {
return array.filter(i => i === num).length === 5;
}
function getNumbersThatAppearFiveTimes(array) {
return array.reduce((prev, curr) => {
if (!prev.includes(curr) && equalFive(array, curr)) {
return [...prev, curr]
}
return prev;
}, []);
}
console.log(getNumbersThatAppearFiveTimes(numbers))

答案 2 :(得分:1)
这是一个使用lodash的解决方案,它已经内置了许多这样的功能,因此您的代码库可以更清晰。
const inputArray = [187,187,187,187,187,62,62,43,43,43,43,43,5,5,5];
const inputValue = 5;
const count = _.countBy(inputArray); // count each instance of values
const equality = _.pickBy(count, x => x === inputValue); // filter values with 5 appearances
const output = Object.keys(equality).map(Number); // convert to desired format
console.log(output); // [43, 187]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
答案 3 :(得分:0)
var input_array = [187, 187, 187, 187, 187, 62, 62, 43, 43, 43, 43, 43, 5, 5, 5];
//Sort input array
input_array.sort();
var output_array = [];
var count = 0;
var current = input_array[0];
for(var i = 0; i < input_array.length; i++){
//Loop until change to next number
//Check if total quantity equals 5
if(input_array[i] != current){
//save into output if equals 5
if(count == 5){
output_array.push(current);
}
//reset counter
current = input_array[i];
count = 1;
}else{
count++;
}
}
console.log(output_array);
&#13;
答案 4 :(得分:0)
使用Array#reduce()将计数映射到Map对象,然后使用Array#filter()返回结果
function scr(array, n) {
const counts = array.reduce((a, c) => a.set(c, (a.get(c) || 0) + 1), new Map);
return [...counts.keys()].filter(v => counts.get(v) >= n);
}
const input = [187, 187, 187, 187, 187, 62, 62, 43, 43, 43, 43, 43, 5, 5, 5];
console.log(scr(input, 5))
答案 5 :(得分:0)
您可以使用计数器并使用单个循环过滤 nth 计数元素。
function scr(array, n) {
var count = Object.create(null);
return array.filter(v => (count[v] = (count[v] || 0) + 1) === n);
}
console.log(scr([187, 187, 187, 187, 187, 62, 62, 43, 43, 43, 43, 43, 5, 5, 5], 5));
&#13;