BY Akash Kava31 Mar 2021 Edit
How do you calculate Match Percentage in an Array?

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!

BY Akash Kava
LikeCommentSave
LikeCommentSaveShare
0
Categories
General
YantraJS
Developer Guides
Tutorials
Web Atoms Updates

POPULAR POSTS
17 Mar 2021
LATEST ACTIVITY
Simmi Kava
commented this post.
Simmi Kava
liked this post.
Show more
ARCHIVES
2025
2024
2023
2022
TAGS
javascript (56)
developer (25)
javascriptdeveloper (16)
Xamarin.Forms (16)
Html (14)
typescript (12)
webatoms (12)
xamarin (11)
coding (10)
web-atoms (10)
arrays (9)
android (8)
javascript-developer (8)
csharp (7)
dotnet (7)
css (6)
update (6)
dotnet-standard (5)
function (5)
iOS (5)
methods (4)




Web Atoms: JSX (TSX + TypeScript) for Xamarin.Forms, Hot Reload Your App in Production Environment

PlaygroundSamples Repository