Get Unique values from Array

This can be achieved (in AS2 and AS3) in a much simpler manner, using the following function or prototype:

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;
};

For an example i have an array [“Orange”,”Apple”,”Apple”,”Orange”,”Pappaya”],
Would like to get the count of each values [Orange => 2, Apple => 2, Pappaya
=>1]

Once the following function is invoked for this array, it removes the all the
duplicates and generate a new Array with Unique values and it counts.

Usage

var SourceArray=[“Orange”,”Apple”,”Apple”,”Orange”,”Pappaya”]
var NewArray=SourceArray.countValues()
trace(NewArray)//Returns Pappaya,1,Apple,2,Orange,2

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.