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.
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:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
bifurcate()function, which splits values into two groups based on the result of the givenfilterarray. - To implement the function, use
Array.prototype.reduce()andArray.prototype.push()to add elements to groups, based on thefilterarray. - If
filterhas 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.