This content originally appeared on DEV Community and was authored by Mysterio
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.
Lets 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
https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl
This content originally appeared on DEV Community and was authored by Mysterio
Mysterio | Sciencx (2022-07-23T14:57:00+00:00) Finding Occurences of element in array in js. Retrieved from https://www.scien.cx/2022/07/23/finding-occurences-of-element-in-array-in-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.