Exercise 15: Partition Array by Condition
Problem Statement
Create a function `partition(arr, fn)` that divides array into two groups based on condition.
Example: partition([1, 2, 3, 4], n => n % 2 === 0) → [[2, 4], [1, 3]]
Sample Output:
partition([1, 2, 3, 4], n => n % 2 === 0) => [[2, 4], [1, 3]] partition([1, 2, 3], n => n > 2) => [[3], [1, 2]]
Solution
const partition = (arr, fn) => {
const truthy = [], falsy = [];
arr.forEach(item => (fn(item) ? truthy : falsy).push(item));
return [truthy, falsy];
};Explanation
Overall Goal:
- Array ko condition ke basis par partition karna.
Real world:
- Data filtering: separate valid/invalid.
- Grouping: categorize items.