Created
October 3, 2011 18:36
-
-
Save lsauer/1259865 to your computer and use it in GitHub Desktop.
Filter empty elements from an Array or csv string/file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//lo sauer 2011 - lsauer.com | |
//join() is by default: join(',') | |
[1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,,8,,,-2].filter(String).join() | |
>>>"1,2,3,3,0,4,4,5,6,8,-2" | |
//same result for: filter(function(){return 1}); | |
[1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,,8,,,-2].filter(function(){return 1}).join() | |
>>>"1,2,3,3,0,4,4,5,6,8,-2" | |
//to conveniently eliminate null-elements... | |
[1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,,8,,,-2].filter(Number).join() | |
>>>"1,2,3,3,4,4,5,6,8,-2" | |
//same result for function(e){return e}; | |
[1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,,8,,,-2].filter(function(e){return e}).join() | |
>>>"1,2,3,3,4,4,5,6,8,-2" | |
//both methods also get rid off undefined, null etc... | |
[1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,,8,,,undefined,,null,,-2,].filter(Number).join() | |
>>>"1,2,3,3,4,4,5,6,8,-2" | |
//------CSV--------- | |
//when starting out with a csv-string... | |
"1,2,,3,3,3,,,0,,,4,,4,,5,,6,,,,,8,,,-2".split(',') | |
>>>["1", "2", "", "3", "3", "3", "", "", "0", "", "", "4", "", "4", "", "5", "", "6", "", "", "", "", "8", "", "", "-2"] | |
//heed the missing numbers, due to the difference in the arguments passed: [val, key, obj] | |
//parseInt's second parameter is the base to which the Number should be converted to | |
// see http://lsauer.com/2011/09/javascript-binary-to-int-hex-decimal.html | |
"1,2,,3,3,3,,,0,,,4,,4,,5,,6,,,,,8,,,-2".split(',').filter(parseInt) | |
>>>["1", "3", "3", "4", "4", "5", "6", "8", "-2"] | |
//parseFloat has no base argument as second parameter | |
"1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,,8,,,-2".split(',').filter(parseFloat) | |
>>>["1", "2", "3", "3", "4", "4", "5", "6", "8", "-2"] | |
//putting it all together: | |
"1,2,,3,3,3,,,0,,,4,,4,,5,,6,,,,,8,,,-2".split(',').filter(Number).map(parseFloat) | |
>>>[1, 2, 3, 3, 3, 4, 4, 5, 6, 8, -2] | |
//retaining zero values | |
"1,2,,3,3,3,,,0,,,4,,4,,5,,6,,,,,8,,,-2".split(',').filter(String).map(parseFloat) | |
>>>[1, 2, 3, 3, 3, 0, 4, 4, 5, 6, 8, -2] | |
//string-padded example, with the first and last element not being parsable | |
"start {[1,2,,3,3,3,,,0,,,4,,4,,5,,6,,,,,8,,,-2]dsfdsf".split(',').filter(Number).map(parseFloat) | |
[2, 3, 3, 3, 4, 4, 5, 6, 8] | |
//using phptrim (see my other gists)... | |
"start {(1,2,,3,3,3,,,0,,,4,,4,,5,,6,,,,,8,,,-2)dsfdsf".phptrim('{stardsf{}() ').split(',').filter(Number).map(parseFloat) | |
>>>[1, 2, 3, 3, 3, 4, 4, 5, 6, 8, -2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment