Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of times a same value appears in a javascript array

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; } 
like image 913
Donald Duck Avatar asked May 21 '16 16:05

Donald Duck


People also ask

How do you count the number of times a value appears in an array JavaScript?

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 .

How do you count repeated values in an array?

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.

How do you count occurrences in JavaScript?

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.


2 Answers

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 
like image 64
RomanPerekhrest Avatar answered Sep 22 '22 06:09

RomanPerekhrest


Another option is:

count = myArray.filter(x => x == searchValue).length; 
like image 39
Edgy Avatar answered Sep 21 '22 06:09

Edgy