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.

Thursday, February 28, 2008

The beginning of a new era

I have been learning Flex since the last couple of months and I must say that each day has been a new learning experience. Every day before I go to bed, if I try to recollect what new have I learnt today, I have never been short of a topic. Flex is just like an ocean and I have just begun to sail.

I am writing this blog for two reasons. One - for myself; to remember the path that I took to learn the wonderful technology. And two - for the world. As I am learning, I have seen many people have faced similar problems that I face during my research everyday. And 9 out of 10 times, either I find the answer to my problem in Flex's Help, or in someone's blog. Well... I am not a kind of genius to write another help file (and Flex's help is pretty comprehensive anyway ;)). So I decided to do my bit to serve the ever growing Flex community by blogging my problems and the workarounds/solutions I used.

I'm really excited to start this off!!! Hope I continue to blog regularly and I succeed in my journey ~ As Johnny Walker says: A Journey of a Thousand Miles Begins with a Single Step. I have kept my first step. Lets see how long this journey goes.

All the best to myself and the rest of the world :)