Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Omitting false values while constructing string in JavaScript



We have an array that contains some string values as well as some false 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 false values.

Example

The code for this will be −

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

The output in the console −

Hereisanexampleofasentence
Updated on: 2020-10-14T07:51:58+05:30

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements