Bifurcate Array Based on Values

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to bifurcate an array based on given values using JavaScript. The lab will demonstrate how to use the Array.prototype.reduce() method and Array.prototype.push() method to add elements to two groups, based on a given filter. 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/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28171{{"`Bifurcate Array Based on Values`"}} javascript/data_types -.-> lab-28171{{"`Bifurcate Array Based on Values`"}} javascript/arith_ops -.-> lab-28171{{"`Bifurcate Array Based on Values`"}} javascript/comp_ops -.-> lab-28171{{"`Bifurcate Array Based on Values`"}} javascript/array_methods -.-> lab-28171{{"`Bifurcate Array Based on Values`"}} javascript/higher_funcs -.-> lab-28171{{"`Bifurcate Array Based on Values`"}} end

Function to Split Array into Two Groups

To use this function to split an array into two groups based on the values, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the bifurcate() function, which splits values into two groups based on the result of the given filter array.
  3. To implement the function, use Array.prototype.reduce() and Array.prototype.push() to add elements to groups, based on the filter array.
  4. If filter has a truthy value for any element, add it to the first group; otherwise, add it to the second group.

Here is the code for the bifurcate() function:

const bifurcate = (arr, filter) =>
  arr.reduce(
    (acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc),
    [[], []]
  );

You can call the bifurcate() function with an array of values and a corresponding filter array to split the values into two groups. For example:

bifurcate(["beep", "boop", "foo", "bar"], [true, true, false, true]);
// [ ['beep', 'boop', 'bar'], ['foo'] ]

Summary

Congratulations! You have completed the Bifurcate Array Based on Values lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like