I would like to know if there is a native javascript code that does the same thing as this:
function f(array,value){ var n = 0; for(i = 0; i < array.length; i++){ if(array[i] == value){n++} } return n; }
To check how many times an element appears in an array:Use the forEach() method to iterate over the array. Check if the current element is equal to the specific value. If the condition is met, increment the count by 1 .
Use the reduce() method to count the duplicates in an array, passing it an empty object as the initial value for the accumulator. On each iteration, increment the count of the value in the object, or initialize the value to 1 . Copied! const arr = ['one', 'two', 'one', 'one', 'two', 'three']; const count = arr.
In JavaScript, we can count the string occurrence in a string by counting the number of times the string present in the string. JavaScript provides a function match(), which is used to generate all the occurrences of a string in an array.
There might be different approaches for such purpose.
And your approach with for
loop is obviously not misplaced(except that it looks redundantly by amount of code).
Here is some additional approaches to get the occurrence of a certain value in array:
Using Array.forEach
method:
var arr = [2, 3, 1, 3, 4, 5, 3, 1]; function getOccurrence(array, value) { var count = 0; array.forEach((v) => (v === value && count++)); return count; } console.log(getOccurrence(arr, 1)); // 2 console.log(getOccurrence(arr, 3)); // 3
Using Array.filter
method:
function getOccurrence(array, value) { return array.filter((v) => (v === value)).length; } console.log(getOccurrence(arr, 1)); // 2 console.log(getOccurrence(arr, 3)); // 3
Another option is:
count = myArray.filter(x => x == searchValue).length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With