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.
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:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
Array.prototype.reduce()andArray.prototype.push()methods to add elements to groups. This is based on the value returned by the given functionfnfor each element. - If
fnreturns 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.