Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.join() with condition

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"

like image 872
Nomi Avatar asked Dec 25 '22 05:12

Nomi


1 Answers

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(', ');
like image 159
Tushar Avatar answered Jan 06 '23 15:01

Tushar