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
Top comments (8)
By the way, that
else { continue }
at the end of the loop is completely useless.This is also a better approach thank you
Your code returns (if we fix the spelling mistake):
Also, the
else
clause in your code is entirely redundant, and the target will not be found if it appears at index 0.Overall, this problem would seem a good use case for reduce:
Can you please write the whole code with if statement
Like this?
Yeah thank you sir
I also want to know is there any performance or any type of difference in my way of implementing and your way of implementing or its just about cleaner way of writing this ?
A quick check on Chrome shows that the reduce method is around 70% faster
Okayss