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

前端 未结 8 2102
执笔经年
执笔经年 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:03
    let ar = [2,2,3,1,4,9,5,2,1,3,4,4,8,5];
    
    const countSameNumber = (ar: any, findNumber: any) => {
        let count = 0;
        ar.map((value: any) => {
            if(value === findNumber) {
                count = count + 1;
            }
        })
        return count;
    }
    
    
    let set = new Set(ar);
    for (let entry of set) {
        console.log(entry+":", countSameNumber(ar, entry));
    }
    
    0 讨论(0)
  • 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
      
    0 讨论(0)
  • 2020-12-14 08:14

    Here is my solution without using an additional object and using reduce:

    const occurrencesOf = (number,numbers) => numbers.reduce((counter, currentNumber)=> (number === currentNumber ? counter+1 : counter),0);
    occurrencesOf(1, [1,2,3,4,5,1,1]) // returns 3
    occurrencesOf(6, [1,2,3,4,5,1,1]) // returns 0
    occurrencesOf(5, [1,2,3,4,5,1,1]) // returns 1
    
    0 讨论(0)
  • 2020-12-14 08:17

    You may want to use indexOf() function to find and count each value in array

    function g(array,value){
      var n = -1;
      var i = -1;
      do {
        n++;
        i = array.indexOf(value, i+1);
      } while (i >= 0  );
    
      return n;
    }
    
    0 讨论(0)
  • 2020-12-14 08:18

    You can also use forEach

    let countObj = {};
    let arr = [1,2,3,1,2,3,4];
    
    let countFunc = keys => {
      countObj[keys] = ++countObj[keys] || 1;
    }
    
    arr.forEach(countFunc);
    
    // {1: 2, 2: 2, 3: 2, 4: 1}
    
    0 讨论(0)
  • 2020-12-14 08:23

    Another option is:

    count = myArray.filter(x => x == searchValue).length;
    
    0 讨论(0)
提交回复
热议问题