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

前端 未结 8 2103
执笔经年
执笔经年 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:24

    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;
    }, {});
    
    0 讨论(0)
  • 2020-12-14 08:24
    const arr = ["a", "a", "a", "b", "b", "b", "b", "c", "c", "c"];
    count = 0;
    
    function countValues(array, countItem) {
      array.forEach(itm => {
        if (itm == countItem) count++;
      });
      console.log(`${countItem} ${count}`);
    }
    countValues(arr, "c");
    
    0 讨论(0)
提交回复
热议问题