Finding Occurences of element in array in js

Shubham Tiwari
FAUN — Developer Community 🐾
2 min readJul 23, 2022

--

Hello guys today i want to show you how to find number of occurence of element in an array in javascript and also their index.

Let get started…

Code -

let array = [6,1,4,4,2,8,3,4,4,4,5,10,5,9,11,
6,1,4,4,2,8,3,4,4,4,5,10,5,9,11,6,1,4,4,2,8,3,4,4,4,5,10,5,9,11];
let target = 4
const occurences = (array,target) => {
let result = 0
let index = []
for (let i = 1; i <= array.length + 1; i++) {
if(array[i] === target){
result++
index.push(i)
}
else{
continue
}
}
return `${target} occured ${result.length} times at indexes - ${index}`
}
console.log(occurences(array,target))

Output -

4 occured 15 times at indexes - 2,3,7,8,9,17,18,22,23,24,32,33,37,38,39
  • So first we have created an arrow function with two parameter namely array and target.Array will be the one which we are going to perform our searching for occurences and target is the element we want to find how many times it occured in the array and which index.
  • We created two variable result and index.Result will hold the target occurence number and index will hold the indexes of that occurence in the array.
  • We created a for loop which will iterate through the array to last element.
  • Then we have created a condition with “if” as if the element at current index element is equal to the target element then increase the result with 1 and push the index of that element to the index array and if the element at current index is not equal to the target element then continue the iteration to the next element using “continue” keyword.
  • In the end we have return the statement using string interpolation with number of occurences and their indexes.

Thats it for this post.
THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE ANY SUGGESTION FOR IMPROVEMENT, PLEASE MENTION IT IN THE COMMENT SECTION.
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ → https://www.buymeacoffee.com/waaduheck

Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo

https://dev.to/shubhamtiwari909/e-quotes-3bng

If this post was helpful, please click the clap 👏 button below a few times to show your support for the author 👇

🚀Developers: Learn and grow by keeping up with what matters, JOIN FAUN.

--

--

A Frontend Developer with Knowledge of HTML,CSS,JavaScript,TailwindCSS,Bootstrap,React JS,RWD,Web Apps and Performing Operation with API Data