array_count_values in Actionscript

In PHP there is a very useful function called array_count_values. It sorts an array by returning a 2 dimensional array consisting of non duplicate elements as keys, and values determined by how many times these elements appeared in the original array.

So, for example, an array [“red”,”green”,”blue”,”red”] would be converted into [“red” => 2, “green” =>1, “blue” => 1]. Duplicate elements are removed and the new array indicates how many times each, now unique value occurred in the array.

Unfortunately, Actionscript has no such function built in, so I made one. It is a modification of Senocular’s array.unique() prototype (which you can find in his Actionscript library), however rather than simply returning a unique array, it returns the 2 dimensional array mentioned above.

Array.prototype.countValues = function ()
{
	var z, x = this.length, c = false, a = [], d = [];
	while (x--)
	{
		z = 0;
		while (z < x)
		{
			if (this[x] == this[z])
			{
				c = true;
				d.push (this[x]);
				break;
			}
			z++;
		}
		if (!c) a.push ([this[x], 1]);
		else c = false;
	}
	y = a.length;
	while (y--)
	{
		q = 0;
		while (q < d.length)
		{
			if (a[y][0] == d[q]) a[y][1]++;
			q++;
		}
	}
	return a;
};

Example useage:

var myArray:Array = new Array ("the", "cat", "sat", "on", "the", "mat");
var newArray:Array = myArray.countValues ();
trace (newArray);
// Returns [[mat,1],[on,1],[sat,1],[cat,1],[the,2]]

This prototype should work with arrays of objects, though it was designed for simple datatypes such as strings.

Note: This prototype is case sensitive for strings. If you want it to be case insensitive, just modify to, for example:

if (a[y][0].toLowerCase () == d[q].toLowerCase ()) a[y][1]++;
Posted on 20 Jun 2007
Posted in
Tagged
2 Comments
0 Trackbacks

Meta

AS2 Array count values was posted on June 20th 2007 in the category Code / Code and tagged; , , .

You can Leave a comment.

Twitter <follow>

March 18th 2010 - 5:29pm

We've missed you Morris: RT @memotv: This guy is nuts. New trailer for Chris Morris' jihadist comedy Four Lions http://is.gd/aNzki

Discussion

2 Responses to AS2 Array count values

Leave a Reply

  1. Dan 10 months ago

    Could you convert this to AS3… I don’t know mush AS2 since I’ve just started learning.

    Reply to this comment

  2. sharat achary 3 months ago

    Hey thought I might not be using this code, but it did helped me how to use while loops in better way……
    Thanks anyways.

    Reply to this comment