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 :: math from string js 
Javascript :: match regex 
Javascript :: get largest no in the array javascript 
Javascript :: give a prop only if pass condition 
Javascript :: copia independiente array javascript 
Javascript :: how to upload file with button react 
Javascript :: what is a block in javascript 
Javascript :: Setting darkmode using Tailwind 
Javascript :: javascript /g 
Javascript :: binary to decimal javascript 
Javascript :: adb.exe: more than one device/emulator react native 
Javascript :: vanilla js append new element 
Javascript :: for in loop javascript 
Javascript :: javascript floating point addition 
Javascript :: how to set expire time of jwt token in node js 
Javascript :: validate password in nodejs 
Javascript :: sequelize get data 
Javascript :: angular on back skip routes 
Javascript :: filter object array 
Javascript :: URLSearchParams 
Javascript :: javascript isempty 
Javascript :: Getting Error “cannot read property split of null” 
Javascript :: bind method in javascript 
Javascript :: toggle button in angularjs bootstrap 
Javascript :: it each jest 
Javascript :: Add jquery in extension 
Javascript :: datatable on error.dt 
Javascript :: 8ball javascript 
Javascript :: window.open 
Javascript :: ejs public 
ADD CONTENT
Topic
Content
Source link
Name
2+8 =