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

前端 未结 8 2258
执笔经年
执笔经年 2020-12-14 07:27

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 < arr         


        
8条回答
  •  不思量自难忘°
    2020-12-14 08:05

    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
      

提交回复
热议问题