How to count the number of identical numbers in an array using a function?
-
You need to calculate using a function that receives an array and a specific number, the number of this specific number in the array of numbers.JavaScript Anonymous, Sep 27, 2019
-
const count = (arr, val) => arr.filter(n => n === val).length;
// или
const count = (arr, val) => arr.reduce((acc, n) => acc + (n === val), 0);
It is possible and in a more general form, we consider everything:
const count = arr => arr.reduce((acc, n) => acc.set(n, (acc.get(n) || 0) + 1), new Map);
const arr = [ 1, 1, 1, 2, 2, 9, 9, 9, 9, 7, 'hello, world!!', 'hello, world!!' ];
const counted = count(arr);
console.log(counted.get(1)); // 3
console.log(counted.get(9)); // 4
console.log(counted.get('hello, world!!')); // 2
UPD. In the comments, it was suggested that it would be nice to do something with the values that were not represented in the original data. Let's substitute 0:
function Counter(data, key = x => x) {
const counted = new Map;
for (const n of data) {
const k = key(n);
counted.set(k, (counted.get(k) || 0) + 1);
}
return k => counted.get(k) || 0;
}
You can use it like this:
const arr = [ 1, 1, 1, 2, 2, 9, 9, 9, 9, 7, 'hello, world!!', 'hello, world!!' ];
const counted = Counter(arr);
console.log(counted(1)); // 3
console.log(counted(10)); // 0
Or like this:
<span class="color">red</span>
<span class="color">green</span>
<span class="color">red</span>
<span class="color">red</span>
const counted = Counter(document.querySelectorAll('.color'), el => el.innerText);
console.log(counted('red')); // 3
console.log(counted('blue')); // 0Anonymous -
nums.reduce((acc, n) => n === numToFind ? acc + 1 : acc, 0);
Anonymous -
function countValueInArray(yourArrName, inputValue) {
return arr.reduce((count, item) => count + (item === inputValue), 0)
};Anonymous
3 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!