Introduction
In this lab, we will explore how to partition an array based on a provided function using JavaScript. We will use the Array.prototype.reduce() method to accumulate the partitioned values into an array while checking for changes in the output of the provided function. By the end of this lab, you will have a solid understanding of how to partition arrays in JavaScript.
Partition Array Algorithm
To partition an array, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Apply the provided function
fnto each value in the given arrayarr. - Split the array each time
fnreturns a new value. - Use
Array.prototype.reduce()to create an accumulator object that holds the resulting array and the last value returned fromfn. - Use
Array.prototype.push()to add each value inarrto the appropriate partition in the accumulator array. - Return the resulting array.
Here is the code implementation:
const partitionBy = (arr, fn) =>
arr.reduce(
({ res, last }, v, i, a) => {
const next = fn(v, i, a);
if (next !== last) res.push([v]);
else res[res.length - 1].push(v);
return { res, last: next };
},
{ res: [] }
).res;
Example usage:
const numbers = [1, 1, 3, 3, 4, 5, 5, 5];
partitionBy(numbers, (n) => n % 2 === 0); // [[1, 1, 3, 3], [4], [5, 5, 5]]
partitionBy(numbers, (n) => n); // [[1, 1], [3, 3], [4], [5, 5, 5]]
Summary
Congratulations! You have completed the Partition Array lab. You can practice more labs in LabEx to improve your skills.