473,581 Members | 2,488 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 110925
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','yo u','me','me','t hem','them','ot hers'];
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.c om> wrote in message
news:42******** *************** @news.euronet.n l...
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.n l...
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','yo u','me','me','t hem','them','ot hers'];
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.n l...
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','yo u','me','me','t hem','them','ot hers'];
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','yo u','me','m*e',' them','them','o thers'];
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','th em',
'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
2113
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
6371
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 array.split(";") command and proceeded to update the elemment by assigning the null value to the arrayindex array=""
6
4129
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 end is found is less efficient than using sizeof operator , since size of the array is completely determined at compile time. i don't quite...
3
5179
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 element of the array? Thanks, Thomas -- Posted via NewsDemon.com - Premium Uncensored Newsgroup Service
4
6955
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
2351
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 please help? Thanks,
3
2530
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 time I use lower_bound and upper_bound to find the actual data within the map. However in some cases no data exist in the range. What happens in this...
0
1079
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: <start-para> <heading>Head Text</heading> <heading>Some text</heading>
3
18424
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 php? Thanks
0
7800
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8153
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7902
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8178
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6558
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5679
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3806
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3830
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1405
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.