473,385 Members | 2,014 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Count elements in an array

How can you caount the number of occurrences of elements in an array? For
example

var arr1 =
[1,5,1,1,5,2,4,5,2,3,2,4,2,4,2,3,2,3,2,4,2,3,2,4,2, 5,1,4,2,4,2,3,2,4,1];

how can I count how many 1s, 2s, 3s, etc.?

Despite the example, I never actually know what elements (and how many) the
array holds, which means, that the following is NOT a solution for me:

for( var i =0; i <arr1.length; i++) {
if (arr1[i] ==1) cnt1++;
if (arr1[i] ==2) cnt2++;
etc.
}

Thanks,

Rafal
Jul 23 '05 #1
9 110916
Rafal Konopka wrote:
How can you caount the number of occurrences of elements in an array?
For example

var arr1 =
[1,5,1,1,5,2,4,5,2,3,2,4,2,4,2,3,2,3,2,4,2,3,2,4,2, 5,1,4,2,4,2,3,2,4,1];

how can I count how many 1s, 2s, 3s, etc.?


http://www.php.net/manual/en/functio...unt-values.php
JW

Jul 23 '05 #2
Janwillem Borleffs wrote:
http://www.php.net/manual/en/functio...unt-values.php


Sorry, thought I was reading a PHP newsgroup...
JW

Jul 23 '05 #3
Ivo
"Rafal Konopka" wrote
How can you caount the number of occurrences of elements in an array? For
example

var arr1 =
[1,5,1,1,5,2,4,5,2,3,2,4,2,4,2,3,2,3,2,4,2,3,2,4,2, 5,1,4,2,4,2,3,2,4,1];

how can I count how many 1s, 2s, 3s, etc.?

Despite the example, I never actually know what elements (and how many) the array holds


Several approaches exist. This one retuns an object with the array values as
keys and the number of times they occur as values:

function countvalues(a) {
var b = {}, i = a.length, j;
while( i-- ) {
j = b[a[i]];
b[a[i]] = j ? j+1 : 1;
}
return b;
}

var arr=['you','you','you','me','me','them','them','others'];
alert( countvalues(arr)['you'] ); // 3

hth
--
Ivo
http://4umi.com/
Jul 23 '05 #4
Rafal Konopka wrote:
How can you caount the number of occurrences of elements in an array?
For example

var arr1 =
[1,5,1,1,5,2,4,5,2,3,2,4,2,4,2,3,2,3,2,4,2,3,2,4,2, 5,1,4,2,4,2,3,2,4,1];

how can I count how many 1s, 2s, 3s, etc.?


The following might be useful:

var arr1 =
[1,5,1,1,5,2,4,5,2,3,2,4,2,4,2,3,2,3,2,4,2,3,2,4,2, 5,1,4,2,4,2,3,2,4,1];
var count = [];
var msg = '';

for (var i = 0; i < arr1.length; i++) {
if (count[arr1[i]]) {
count[arr1[i]] += 1;
} else {
count[arr1[i]] = 1;
}
}

for (i in count) msg += i + ' occurres ' + count[i] + ' times\n';
alert(msg);
JW

Jul 23 '05 #5
Thank,

I'll give it a whirl and see what happens

Rafal
"Janwillem Borleffs" <jw@jwscripts.com> wrote in message
news:42***********************@news.euronet.nl...
var arr1 =
[1,5,1,1,5,2,4,5,2,3,2,4,2,4,2,3,2,3,2,4,2,3,2,4,2, 5,1,4,2,4,2,3,2,4,1];
var count = [];
var msg = '';

for (var i = 0; i < arr1.length; i++) {
if (count[arr1[i]]) {
count[arr1[i]] += 1;
} else {
count[arr1[i]] = 1;
}
}

for (i in count) msg += i + ' occurres ' + count[i] + ' times\n';
alert(msg);
JW

Jul 23 '05 #6
Ivo, It's a nice and crisp solution, but I cannot pass a parameter to the
function as I never know what elements the array holds.

Essentiall, I was wondering if the newer versions of javascript had
something similar to (and oh-so-useful) Perl's

$count{$val}++;

vivifying the hash by creating the key (the unknown element) and value (its
count).

Rafak

"Ivo" <no@thank.you> wrote in message
news:42***********************@news.wanadoo.nl...
Several approaches exist. This one retuns an object with the array values as keys and the number of times they occur as values:

function countvalues(a) {
var b = {}, i = a.length, j;
while( i-- ) {
j = b[a[i]];
b[a[i]] = j ? j+1 : 1;
}
return b;
}

var arr=['you','you','you','me','me','them','them','others'];
alert( countvalues(arr)['you'] ); // 3

hth
--
Ivo
http://4umi.com/

Jul 23 '05 #7
Rafal Konopka wrote:
Ivo, It's a nice and crisp solution, but I cannot pass a parameter to the function as I never know what elements the array holds.

Essentiall, I was wondering if the newer versions of javascript had
something similar to (and oh-so-useful) Perl's

$count{$val}++;

vivifying the hash by creating the key (the unknown element) and value (its count).

Rafak

"Ivo" <no@thank.you> wrote in message
news:42***********************@news.wanadoo.nl...
Several approaches exist. This one retuns an object with the array
values as
keys and the number of times they occur as values:

function countvalues(a) {
var b = {}, i = a.length, j;
while( i-- ) {
j = b[a[i]];
b[a[i]] = j ? j+1 : 1;
}
return b;
}

var arr=['you','you','you','me','me','them','them','others'];
alert( countvalues(arr)['you'] ); // 3

hth
--
Ivo
http://4umi.com/


Maybe...

Array.prototype.countvalues = function(k)
{
var b = {}, i = this.length, j;
while( i-- )
{
j = b[this[i]];
b[this[i]] = j ? j+1 : 1;
}
return b[k];
}

var arr=['you','you','you','me','m*e','them','them','others '];
alert( arr.countvalues('you') ) // 3

This won't distinguish between string/numeric primitives ('4' / 4)
however; don't think you can hash with these as JS objects treat
string/numeric integer subscripts similarly.

Jul 23 '05 #8
Rafal Konopka wrote:
Ivo, It's a nice and crisp solution, but I cannot pass a parameter to the
function as I never know what elements the array holds.


If you just want to get a reduced array with unique elements and
the count of occurrences, then Ivo's solution actually does
exactly that. You just need to modify the output:

<script type="text/javascript">
function countvalues(a) {
var b = {}, i = a.length, j;
while( i-- ) {
j = b[a[i]];
b[a[i]] = j ? j+1 : 1;
}
return b; // an object of element:count arrays
}

var arr=['you','you','me','you',
'me','them','them',
'others','you'];

var a = countvalues(arr);
var msg='';

// To see how many times each element appears
for (elem in a){
msg += '\n' + elem + ' : ' + a[elem];
}
alert(msg);

// To see how many times a particular element appears
alert( countvalues(arr)['you'] ); // 4

</script>

--
Rob
Jul 23 '05 #9

Thanks to all who replied to my question (counting elements of an array).
It was in fact very educational.

Rafal
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Nathan Rose | last post by:
Here's my problem. I am reading from a text file using this: if (!file_exists($file)) { echo "Don't exist\n"; return false; } $fd = @fopen($file, 'r'); if (!is_resource($fd))
5
by: effendi | last post by:
I wrote a simple script to remove an element of an array but I don't think this is the best way to go about it. I have a list of about five elements seperated by ";" I split the array using...
6
by: Herrcho | last post by:
in K&R Chapter 6.3 it mentions two methods to calculate NKEYS. and points out the first one which is to terminate the list of initializers with a null pointer, then loop along keytab until the...
3
by: thomasp | last post by:
If I have an array declared as Dim aryTargets(99) as integer, can I get the count of how many of the elements actually are filled without looping through the array and testing the value of each...
4
by: ralf321 | last post by:
Hello! i want to count elements in xslt. All with meta=13 contains a AND meta 14 contains b but it dont work any Idee why? Thanks. i try it with count(object/node/data)
2
by: Jon | last post by:
Hello all, I have a 2D array called Info. This is of variable size and I'm struggling to find out how to count the number of elements in the first dimention. I've tried all sorts. Can anyone...
3
by: Henrik Goldman | last post by:
I have a map structure containing the following information: ->first contains a time_t and is used for lookups ->second holds my associated data to this time When calculating averages over...
0
MarkoKlacar
by: MarkoKlacar | last post by:
Hi! I have a problem, I want to select the number of elements within an element. All I need is the number (count), and I just want to it once for "one row" so to speak. Picture this XML file:...
3
by: doc1355 | last post by:
I have a XML file that is automaticaly generated from a database. It contains variable numbers of <product>.....</product> element. How can I count number of "<product>.....</product>" elements in...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.