I'm using YUI3 for the implementation of this, so some of what I'm doing is going to be YUI3 specific, and I'm going to assume that arguments to my methods are YUI3 nodes.
Traditionally, you'd simply iterate over the options of the list, and look for selected items, like so:
This has the benefit of being fairly straight-forward, but it's not the best answer to the problem. For the best solution, and the more computer-sciency solution, we need to look into the realm of map-reduce. Part of the reason MapReduce is such a great solution to this problem is because many newer browsers are implementing map-reduce functionality in native code, allowing them to largely out perform functions like the one above, particularly on large datasets. Further, any good platform library will offer an implementation of the map and reduce functions that will be executed if the native call isn't available.
A quick explanation of the Map and Reduce functionality:
As stated, Y.Array.map and Y.Array.reduce, a part of the collection module in YUI3, will defer to native implementations, if possible. The argument lists are as follows:
- Array - This can't be a NodeList, hence the call the Y.NodeList.getDOMNodes
- function - The function to execute on each element of the argument array, this should return a single value.
- context - optional argument for the context to run the function under, defaults to the window object
- Array - The array, generally output by the map function, that you wish to reduce
- Initial Value - The initial value for the reduce function, this will be the seed value for the first parameter of the argument function.
- Function - Function to execute to reduce the values.
Map-Reduce is a really interesting tool, and while it shines best in a clustering environment, on something like Hadoop, a good understanding of the technique can be helpful even on smaller applications. I will most likely have a more in-depth look at a more involved map-reduce problems up fairly soon.