Bifurcate Array Based on Function

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 a given filtering function in JavaScript. We will use the Array.prototype.reduce() method and the Array.prototype.push() method to split the values of the array into two groups based on whether the filtering function returns a truthy value or not. This lab is designed to enhance your understanding of higher-order functions and array manipulation 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/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28170{{"`Bifurcate Array Based on Function`"}} javascript/data_types -.-> lab-28170{{"`Bifurcate Array Based on Function`"}} javascript/comp_ops -.-> lab-28170{{"`Bifurcate Array Based on Function`"}} javascript/higher_funcs -.-> lab-28170{{"`Bifurcate Array Based on Function`"}} end

Function to Split an Array into Two Groups

To split an array into two groups based on the result of a given function, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the Array.prototype.reduce() and Array.prototype.push() methods to add elements to groups. This is based on the value returned by the given function fn for each element.
  3. If fn returns a truthy value for any element, add it to the first group. Otherwise, add it to the second group.

Here's the code:

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

For example, if you call bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'), the function will return [ ['beep', 'boop', 'bar'], ['foo'] ].

Summary

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

Other JavaScript Tutorials you may like