Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript Count the occurrences of a value in an array

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);

// Examples
countOccurrences([2, 1, 3, 3, 2, 3], 2);                // 2
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a');  // 3
Comment

count occurence in array js

// The initial array we want to count occurences
var initial = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];  

// The count array asked for
var count = Array.from(new Set(initial)).map(val => initial.filter(v => v === val).length);  

// Outputs [ 3, 5, 1, 1 ]
Comment

count number of times an element is occuring in an array in javascript

Array.prototype.frequencies = function() {
    var l = this.length, result = {all:[]};
    while (l--){
       result[this[l]] = result[this[l]] ? ++result[this[l]] : 1;
    }
    // all pairs (label, frequencies) to an array of arrays(2)
    for (var l in result){
       if (result.hasOwnProperty(l) && l !== 'all'){
          result.all.push([ l,result[l] ]);
       }
    }
    return result;
};

var freqs = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].frequencies();
alert(freqs[2]); //=> 5
// or
var freqs = '1,1,2,one,one,2,2,22,three,four,five,three,three,five'
             .split(',')
             .frequencies();
alert(freqs.three); //=> 3
Comment

count occurence in array js

var set = Array.from(new Set(initial));  

//set = [5, 2, 9, 4]
Comment

PREVIOUS NEXT
Code Example
Javascript :: filter data from object 
Javascript :: js date format 
Javascript :: usestate previous state 
Javascript :: hammerjs 
Javascript :: react-particles-js not working 
Javascript :: jquery get data element 
Javascript :: JSE Data 
Javascript :: javascript filter method arrow function 
Javascript :: bootstrap 4 open tab when opening modal 
Javascript :: remove last tag in dom javascript 
Javascript :: convert image url to base64 javascript without canvas 
Javascript :: flutter post request 
Javascript :: angular 7 selected 
Javascript :: js event handlers 
Javascript :: javascript eval() function 
Javascript :: ForEach Element with Function or Lambda 
Javascript :: react select dropdown 
Javascript :: how to search and filter js 
Javascript :: Selectores de jQuery CSS básicos 
Javascript :: get latlong of address in here map api javascript 
Javascript :: JavaScript querySelector - By Tag name 
Javascript :: server smtp 
Javascript :: random math js 
Javascript :: js export options 
Javascript :: javascript parallax effect 
Javascript :: one line if statement javascript 
Javascript :: react usereducer hook 
Javascript :: reset event listener javascript 
Javascript :: boolean javascript 
Javascript :: Clone Array Using Spread Operator 
ADD CONTENT
Topic
Content
Source link
Name
3+3 =