JavaScript: Delete Array Elements
As part of a freelancing project on [oDesk] [oDesk Profile], I am currently working on a couple of simple JavaScript utilities for text processing. A common function in all these utilities is to get a list of non-blank lines from an HTML `textarea`. The simplest way to get a list of lines from a `textarea` is:
var lines = $('#textarea_id').val().split('\n');
But with this input: Asad Jibran Ahmed Pakistan, Lahore Web Developer it produces the output:
["Asad Jibran Ahmed", "", "Pakistan, Lahore", "", "Web Developer"]
which contains empty lines that need to be removed. A Google search for 'javascript delete array element' led me to a post by Wolfram on his blog [Pythoneer][]. He shows how to delete an array element using the `array.splice` function: > var list = [4,5,6]; > list.splice(1, 1); // Remove one element, returns the removed ones. [5] > list [4, 6] Given that I need to remove all the empty elements from an array, my first *naive* attempt resulted in the following gem of JavaScript code:
$.each(lines, function (index, value) { if (value.length == 0) { lines.splice(index, 1); } });
However, every time an element is removed; the array size changes. But since `$.each` checks the array size only **once** at the start, the iteration continues running beyond the array bounds; producing an exception. The fix is simply creating a new array instead of modifying the old one, like so:
var new_lines = []; $.each(lines, function (index, value) { if (value.length != 0) { new_lines.push(value); } });
---- P.S: I just discovered [underscore.js][Underscore.js], a *very* useful JavaScript library that includes some killer functional language features. In the context of this post, the most useful one would be the `_.select`. It iterates over an array and returns a new array with only those elements which pass a test. The code I used above can thus be replaced by this much more concise piece:
var new_lines = _.select(lines, function (val) { return val.length != 0; });
The official documentation for the select function can be read [here][Select Docs]. [oDesk Profile]: https://www.odesk.com/users/~~96fb3b6b8bb094e5 "My oDesk Profile" [Pythoneer]: http://wolfram.kriesing.de/blog/index.php/2008/javascript-remove-element-from-array "JavaScript: Remove element from Array" [Underscore.js]: http://documentcloud.github.com/underscore/ "underscore.js" [Select Docs]: http://documentcloud.github.com/underscore/#select "_.select documentation"