Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  71] [ 1]  / answers: 1 / hits: 130479  / 8 Years ago, sat, may 21, 2016, 12:00:00

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

More From » arrays

 Answers
307

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



[#62077] Thursday, May 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
serena

Total Points: 488
Total Questions: 125
Total Answers: 114

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;