Count the number of times a same value appears in

2020-02-23 07:42发布

问题:

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;
}

回答1:

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
    


回答2:

You could use reduce to get there:

Working example

var a = [1,2,3,1,2,3,4];

var map = a.reduce(function(obj, b) {
  obj[b] = ++obj[b] || 1;
  return obj;
}, {});


回答3:

Another option is:

count = myArray.filter(x => x == searchValue).length;


回答4:

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}


回答5:

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;
}