Hi dev,
In this article we will learn example about Counts the search occurances from an array using javascript. Let's start …
Syntax & Example:
array-count-search-occurances.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>array-count-search-occurances</title>
<link rel="stylesheet" type="text/css" href="../style.css" />
</head>
<body>
<h1>20-array-count-search-occurances!</h1>
<h3>Create a function which counts the search occurances from an array</h3>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Syntax & Example:
script.js
console.log('20-array-count-search-occurances');
// approach 1
/* function countSearchOccurances(arrayToSearch, elementsToSearch) {
// console.log('arrayToSearch: ', arrayToSearch);
// console.log('elementsToSearch: ', elementsToSearch);
let count = 0;
for(let curElement of arrayToSearch) {
if(curElement === elementsToSearch) {
count++;
}
}
// console.log('search count:', count);
return count;
} */
// approach 2
function countSearchOccurances(arrayToSearch, elementsToSearch) {
return arrayToSearch.reduce((countAccumulator, curentSearchElement) => {
let countOccurances = (curentSearchElement === elementsToSearch) ? 1 : 0;
// console.log('countAccumulator', countAccumulator, 'arrayToSearch', arrayToSearch, 'elementsToSearch', elementsToSearch,);
return countAccumulator + countOccurances;
},0)
}
const versionArray = [1, 2, 5, 7, 2];
const versionCount = (countSearchOccurances(versionArray, 2));
console.log('versionCount: ', versionCount);
console.log('---------');
const ageArray = [21, 25, 22, 25, 30, 25, 30];
const ageCount = (countSearchOccurances(ageArray, -25));
console.log('ageCount: ', ageCount);
Hope it can help you…
Categories : JavaScript
Tags : HTML