Introduction
In this lab, we will explore the fundamental concepts of JavaScript programming. You will learn how to write basic JavaScript code and gain an understanding of variables, data types, functions, and control structures. By the end of this lab, you will have a solid foundation in JavaScript programming and be able to apply your knowledge to solve real-world problems.
How to Count Occurrences in JavaScript
To count the number of times a specific value occurs in a JavaScript array, you can use the Array.prototype.reduce() method.
Here is how you can do it:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Copy and paste the following code:
const countOccurrences = (arr, val) =>
arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
- In the code above, the
countOccurrencesfunction takes two arguments: the array to search and the value to count. - The
reduce()method is used to loop through each element in the array and increment a counter each time the specific value is encountered. - To test the function, call it with an array and a value, like this:
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
This will return the number of times 1 occurs in the array [1, 1, 2, 1, 2, 3], which is 3.
Summary
Congratulations! You have completed the Count Occurrences lab. You can practice more labs in LabEx to improve your skills.