How to count the occurrence / frequency of array elements in JavaScript

How to count the occurrence / frequency of array elements in JavaScript

How to count the occurrence / frequency of array elements in JavaScript

<html>
<head>
<title>frequency</title>
<script>
var arr = [1, 1, 2, 19, 2, 19, 4, 5, 2, 5,1, 1, 2, 19, 2, 19, 4, 5, 2, 5,1, 1, 2, 19, 2, 19, 4, 5, 2, 5,1, 1, 2, 19, 2, 19, 4, 5, 2, 5,19, 2, 19, 4, 5, 2, 5,1, 1, 2, 19, 2, 19, 4, 5, 2, 5,1, 1, 2, 19, 2, 19, 4];
var a = [], b = [], prev;

arr.sort();
for ( var i = 0; i < arr.length; i++ ) {
    if ( arr[i] !== prev ) {
        a.push(arr[i]);
        b.push(1);
    } else {
        b[b.length-1]++;
    }
    prev = arr[i];
}
var result = [a, b];
console.log(result);
document.write('[' + result[0] + ']<br>[' + result[1] + ']') 
</script>
</head>
<body>
</body>
</html>

 

Author Biography.

Lokesh Gupta
Lokesh Gupta

Overall 3+ years of experience as a Full Stack Developer with a demonstrated history of working in the information technology and services industry. I enjoy solving complex problems within budget and deadlines putting my skills on PHP, MySQL, Python, Codeigniter, Yii2, Laravel, AngularJS, ReactJS, NodeJS to best use. Through Knowledge of UML & visual modeling, application architecture design & business process modeling. Successfully delivered various projects, based on different technologies across the globe.

News & Blogs

2cda7519f703462a0eabd1c2e84e0001.jpg

Why shouldn’t you wait to jump onto Angular 2?

AngularJs is a JavaScript framework and is widely adopted framework in building Single Page Web A...

8b77d9abe1f73f94ea9f0f008ff988a1.jpeg

Difference between Sets vs. Arrays in JavaScript

The Set object type was introduced in the 2015 ECMAScript specification and is ready to be used i...

7ebe8f7d2be8625f6df997b5d45a86af.jpeg

How to Implement Real Time Notification Using S...

Real time web/versatile application are getting to be well known step by step. Administrations li...