Coding: Counting Occurrences of Elements in an Array using JavaScript
This code snippet is a JavaScript function that can be used to determine the number of occurrences of each element in an array. It’s a useful tool to have in your toolbox when working with arrays, as it allows you to quickly identify the most common elements in a set of data.

Here’s how the code works:
First, the function “occurence” is defined, which takes in an array as an argument.
const occurence = (arr) => {
let arrLength = arr.lengthNext, an empty object called “count” is created to store the number of occurrences of each element in the array.
let count = {}The function then uses a for loop to iterate through the elements of the input array. For each element, the code checks to see if it already exists as a key in the “count” object.
for(let i =0 ; i<arrLength; i++){
let num = arr[i]
count[num] = count[num] ? count[num] + 1 : 1
}If the key does exist, the value associated with that key is incremented by 1. If the key does not exist, it is added to the object with a value of 1.
let num = arr[i]
count[num] = count[num] ? count[num] + 1 : 1After the for loop has finished executing, the function uses the console.log() method to print out the “count” object, which now contains the number of occurrences of each element in the input array.
console.log(count)
}You can test the function by providing an array as an argument.
var arr = [2,3,1,2,38,6,4,0,9]
occurence(arr)For example, if the input array is [2,3,1,2,38,6,4,0,9], the output would be:
{
2: 2,
3: 1,
1: 1,
38: 1,
6: 1,
4: 1,
0: 1,
9: 1
}This shows that the number 2 occurs twice in the array, while all the other numbers occur once.
You can then use the result of this function to draw some insights, for example, you might use it to find the most common element in an array.
Full Code
const occurence = (arr) => {
let arrLength = arr.length
let count = {}
for(let i =0 ; i<arrLength; i++){
let num = arr[i]
count[num] = count[num] ? count[num] + 1 : 1
}
console.log(count)
}
var arr = [2,3,1,2,38,6,4,0,9]
occurence(arr)It’s a simple yet powerful function that can be used in various scenarios such as finding the most frequent element in an array, analysing the patterns in data, or even as a helper function in a larger program.
Happy learning 😄
Do support our publication by following it




