Skip to content

Instantly share code, notes, and snippets.

@drewbourne
Created January 7, 2010 13:04
Show Gist options
  • Save drewbourne/271217 to your computer and use it in GitHub Desktop.
Save drewbourne/271217 to your computer and use it in GitHub Desktop.
package asx.array {
/**
* Preserves unique values in an Array, removes any duplicate values.
*
* @param array Array from which to remove duplicates
* @return Array of unique items
* @example
* <listing version="3.0">
* var values:Array = [1, 1, 1, 2, 3, 5, 5, 8];
* var result:Array = unique(values);
* assertThat(result, equalTo([1, 2, 3, 5, 8]));
* </listing>
*/
public function unique(array:Array, field:String=null):Array {
return field
? inject([], array, uniqueFieldIterator(field)) as Array
: inject([], array, uniqueIterator) as Array;
}
}
import asx.array.contains;
internal function uniqueIterator(memo:Array, value:Object):Array {
if (!contains(memo, value)) {
memo.push(value);
}
return memo;
}
internal function uniqueFieldIterator(field:String):Function
{
var fieldValues:Array = [];
return function(memo:Array, value:Object):Array
{
var fieldValue:* = value[field];
if (!contains(fieldValues, fieldValue))
{
fieldValues.push(fieldValue);
memo.push(value);
}
return memo;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment