We have an array that contains some string values as well as some nullish values.
We are required to write a JavaScript function that takes in this array and returns a string constructed by joining values of the array and omitting nullish values.
Following is our array, with some null and undefined values −
const arr = ["Here", "is", null, "an", undefined, "example", 0, "", "of", "a", null, "sentence"];
Let’s write the code for this function −
Example
const arr = ["Here", "is", null, "an", undefined, "example", 0, "", "of", "a", null, "sentence"]; const joinArray = arr => { const sentence = arr.reduce((acc, val) => { return acc + (val || ""); }, ""); return sentence; }; console.log(joinArray(arr));
Output
Following is the output in the console −
Hereisanexampleofasentence