Introduction
In this lab, we will be exploring the compactJoin function in JavaScript. This function allows you to remove falsy values from an array and join the remaining values into a string. You will learn how to implement this function using Array.prototype.filter() and Array.prototype.join(). By the end of this lab, you will have a better understanding of how to manipulate arrays in JavaScript.
Here's a tip on how to Compact and Join an Array
To start practicing coding, open the Terminal/SSH and type node.
Here's how to remove falsy values from an array and combine the remaining values into a string:
- Use
Array.prototype.filter()to filter out falsy values such asfalse,null,0,"",undefined, andNaN. - Use
Array.prototype.join()to join the remaining values into a string.
const compactJoin = (arr, delim = ",") => arr.filter(Boolean).join(delim);
Then call the function and pass an array as an argument:
compactJoin(["a", "", "b", "c"]); // 'a,b,c'
Summary
Congratulations! You have completed the Compact and Join Array lab. You can practice more labs in LabEx to improve your skills.