Tuesday, March 4, 2008

Using Filters and ForEach in Arrays

This is one of the very handy addition to arrays that has been introduced in AS 3.0. We often need to do some activities with all the elements of the array. In that case, we iterate through the length of the array and do the required task. This is highly memory consuming and at the same time its cumbersome too…

Herez how you can revolutionize the way you deal with arrays:



package {     

import flash.display.Sprite;

public class Array_filter extends Sprite {

public function Array_filter() {
var employees:Array = new Array();
employees.push({name:"Employee 1", manager:false});
employees.push({name:"Employee 2", manager:true});
employees.push({name:"Employee 3", manager:false});
trace("Employees:");
employees.forEach(traceEmployee);
var managers:Array = employees.filter(isManager);
trace("Managers:");
managers.forEach(traceEmployee);
}

private function isManager(element:*, index:int, arr:Array):Boolean {
return (element.manager == true);
}

private function traceEmployee(element:*, index:int, arr:Array):void {
trace("\t" + element.name + ((element.manager) ? " (manager)" : ""));
}
}
}

In the above code, with the FILTER method, you can filter out the data as per need. In the function that filters the data, you get the actual data in the array. You can do the condition check and return “true” if you want the element to be a part of the array and return “false” if you want to remove it from the array.

The ForEach method allows you to browse through all the elements of the array without writing a FOR loop.

No comments: