Compact and Join Array

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28205{{"`Compact and Join Array`"}} javascript/data_types -.-> lab-28205{{"`Compact and Join Array`"}} javascript/arith_ops -.-> lab-28205{{"`Compact and Join Array`"}} javascript/comp_ops -.-> lab-28205{{"`Compact and Join Array`"}} javascript/higher_funcs -.-> lab-28205{{"`Compact and Join Array`"}} end

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 as false, null, 0, "", undefined, and NaN.
  • 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.

Other JavaScript Tutorials you may like