55

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;
}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • 3
    In my honest opinion the for loop you have is a lot cleaner than using `reduce`. There's no single built-in method to do it, the closest you can get is built-in methods that'll loop the array for you. – SeinopSys May 21 '16 at 16:41
  • The function and the loop you provided does what you want it to do. What is the reason you are looking for another method? Is it for performance reasons? Do you have a large array and want to avoid going through the whole array? Knowing what your problem is helps with the answer. – Saeed D. May 21 '16 at 17:55
  • @SaeedD., for counting, you need to inspect every element. – Nina Scholz May 21 '16 at 18:13
  • @Nina, You can also use indexOf to find and count elements. See my working code below. But I like RomanPerekhrest answer and use of filter. – Saeed D. May 21 '16 at 18:21
  • @SaeedD., yes, but it has two loops, one while and one indexof loop. – Nina Scholz May 21 '16 at 18:24
  • @SaeedD: Javascript is a multi paradigm language. The OP used an imperative loop and as you know there's an opposite style called functional programming, which is based on the declarative style. So it's a legitimate question, what alternatives do exist. –  May 21 '16 at 19:53

11 Answers11

81

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
    
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
45

Another option is:

count = myArray.filter(x => x == searchValue).length;
Vencovsky
  • 28,550
  • 17
  • 109
  • 176
Edgy
  • 451
  • 4
  • 8
28

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;
}, {});
omarjmh
  • 13,632
  • 6
  • 34
  • 42
  • 4
    My vote goes to this one since I guess this is exactly the fundamental answer to all questions starting with "give me a solution to find the number of times each... bla bla. – Redu May 21 '16 at 18:55
  • This is definitely the best answer here. concise and gives you a data structure which can be manipulated easier. – ChazUK Aug 19 '22 at 14:24
9

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
8

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}
JJ Cha
  • 89
  • 1
  • 5
3

You could use the Array filter method and find the length of the new array like this

const count = (arr, value) => arr.filter(val => val === value).length
David Ouma
  • 41
  • 3
  • 1
    Can you make the difference to https://stackoverflow.com/a/59573631/7733418 more obvious? I do not get it and you want to avoid the unfavorable impression that might cause. – Yunnosch Jun 08 '22 at 08:38
2
const arr = ["a", "a", "a", "b", "b", "b", "b", "c", "c", "c"];
let count = 0;

function countValues(array, countItem) {
  array.forEach(itm => {
    if (itm == countItem) count++;
  });
  console.log(`${countItem} ${count}`);
}
countValues(arr, "c");
Steve.g
  • 448
  • 4
  • 5
2
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));
}
Jaint Rai
  • 21
  • 1
  • 2
    Hi Rai. Thanks for your answer. Usually answers with an explanation are more welcomed there. Would you like to add an explanation to your answer? – MaxV Nov 09 '20 at 07:19
1

This is how I did mine using just a for loop. It's not as sophisticated as some of the answers above but it worked for me.

function getNumOfTimes(arrayOfNums){
    let found = {}
        for (let i = 0; i < arrayOfNums.length; i++) {
            let keys = arrayOfNums[i].toString()
            found[keys] = ++found[arrayOfNums[i]] || 1
        }

    return found
}

getNumOfTimes([1, 4, 4, 4, 5, 3, 3, 3])

// { '1': 1, '3': 3, '4': 3, '5': 1 }
Sandra
  • 11
  • 2
0

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;
}
Saeed D.
  • 1,125
  • 1
  • 11
  • 23
0
let countValue = 0;

Array.forEach((word) => {
  if (word === searchValue) {
    return countValue ++;
  }
});
console.log(`The number of word 'asdf': ${countValue}`);

I used this code to count the number of a given word in a text which was previously converted into an array.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Panda
  • 1
  • 2