Skip to content

Instantly share code, notes, and snippets.

@nuwansh
Created December 31, 2011 06:11
Remove empty elements from an array in Javascript and join it as string
/**This is example works with only jQuery
* @usecase, if you have array with empty values (ex: ["I", "", "want", "", "to", "go", "" ])
* but you want to return this array as a string.
*/
var myRoom = {
myAction: function(array){
garray = $.grep(array,function(n){
return(n);
});
//join by ' '
return garray.join(' ');
}
};
//Out put is "I want to go"
@nuwansh
Copy link
Author

nuwansh commented Dec 31, 2011

/**
 * Here is the code sample for writing the same with native filter function in ECMA5 (via :https://github.com/laktek )
 */
var myRoom = {
    myAction: function(array){
       return array.filter(function(el){ return el !== "" }).join(" ");
    }
};

var string = myRoom.myAction(["I", "", "want", "", "to", "go", "" ]);
console.log(string);

//Out put is "I want to go"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment