Remove nested arrays in javascript using the prototype library
I have been playing with some drawing code in javascript, storing coordinates and using them later on in the application. My list of coordinates is of the form [ [id1, x1, y1, width1, height1], [id2, x2, y2, width2, height2],…]. A requirement of the application is that a user can delete a set of coordinates from the list. Using prototype.js, I created a simple function to remove the nested array based on the id.
// remove an array from the list based on the id function remove(id, list) { return $A(list).map( function(arr) { if ( $A(arr).first() == id ) { return ; } else { return arr; } }).compact(); }
In your favorite editor, this function can be a one-liner, but spacing helps here for clarity and formatting on the page. Onward! So what's happening? The first thing we do is wrap list with the $A() call to ensure we have access to the extensions prototype gives us for arrays (I'm calling the parameter a list because I'm on an Erlang kick and it has infiltrated my core!). Once extended, we call the map function to iterate through the list and apply the supplied function to each element in the list (in this case it is a list of arrays, so each element passed to the supplied function will be an array as well). Within the supplied function, we are dealing with a single array of the form [id, x, y, width, height], so $A(arr).first() returns the id of the array. This value is compared to the value of the id parameter and if it matches, returns nothing, or 'undefined' in Javascript. If the ids don't match, it returns the array unaltered. As the map function iterates through the list, a new list is created containing the results of the supplied function. So the return value of the map function call is an array. We then call the compact function on the resulting array, which removes any undefined values from the array, essentially leaving only those arrays that did not have the id passed in. This function is fairly specialized; the requirements for the function are fairly specific. A more general function could be written but that is an exercise left to the reader.