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

06df58ced4c8c6bd7e387d3cd0d4167f.png

Top React.js tools for Developers

React continues to grow in popularity by almost 150% from 2017 to 2018. This ...

04dd32c0108d23bf51249aeab490ad84.png

Get a head start with trending Nodejs developer...

To build and run applications, you need different types of runtime environments that help in seve...

99c65279a4f62ad85fb5b8b340077bb3.png

How to Integrate Payumoney Payment Gateway in L...

I am going to explain How to Integrate Payumoney Payment Gateway in Laravel 5. Most of thing are ...