How can I use Array.join()
function with condition
For example:
var name = ['','aa','','','bb'];
var s = name.join(', ');
The output is: ', aa, , ,'bb',
I want to add a condition that will display only words that are not empty: "aa, bb"
You can use Array#filter
to remove empty elements from array and then use Array#join
on filtered array.
arr.filter(Boolean).join(', ');
Here, the callback function to filter
is Boolean constructor. This is same as
// ES5 equivalent
arr.filter(function(el) {
return Boolean(el);
}).join(', ');
As empty strings are falsy in JavaScript, Boolean('')
will return false
and the element will be skipped from the array. And the filtered array of non-empty strings is joined by the glue.
var arr = ['', 'aa', '', '', 'bb'];
var s = arr.filter(Boolean).join(', ');
console.log(s);
You can also use String#trim
to remove leading and trailing spaces from the string.
arr.filter(x => x.trim()).join(', ');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With