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

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

提交回复
热议问题