
JavaScript Code to Calculate Match Percentage in an Array
Array.prototype.some()
The some()
method tests whether at least one element in the array passes the test implemented by the provided function. But it does not provide us any information on how many
items match or all
of them match. In fact, as soon as the first item is matched, it returns true
(condition is not evaluated for all the array elements).
But what if we have a scenario where want to identify if
all
of them matched, or- at least
half
of them matched, or percentage
of matching elements.
Curious to know how can we do it?
Here is a simple match
function that we can use with reduce
to find out the exact matching percentage.
function match(fx) {
return function(pv, current, index, array) {
const fc = fx(current) ? 1 : 0;
if(index === 1) {
const fp = fx(pv) ? 1 : 0;
return fp + fc;
}
if(index === array.length - 1) {
return (pv + fc)/array.length;
}
return pv + fc;
}
}
Output:
// how many items are greater than zero,
console.log(
[1].reduce(match(x => x > 0))
); //1 i.e. 100%
console.log(
[0, 1].reduce(match(x => x > 0))
); //1 i.e. 100%
console.log(
[2, 4, 6].reduce(match(x => x % 2 === 0))
); //1 i.e. 100%
console.log(
[2, 4, 6, 3].reduce(match(x => x % 2 === 0))
); //0.75 i.e. 75%
console.log(
[2, 4, 6, 3, 5].reduce(match(x => x % 2 === 0))
); //0.6 i.e. 60%
Wondering what would be the practical use of this? Machine learning algorithms often depend upon match percentage of different criteria, where such code implementation can be handy.
Hope this helps!
![]() | ![]() | ![]() | ![]() |
Like | Comment | Save | Share |