Array Partition in JavaScript
Level 4296 keystrokes
Partition splits an array into two arrays based on a predicate function.
JavaScript code
// Partition function using reduce1const partition = (arr, predicate) => { // reduce with initial value of two empty arrays2 return arr.reduce( // Destructure accumulator into [pass, fail]3 ([pass, fail], item) => // If predicate is true, add to pass; otherwise add to fail4 predicate(item) ? [[...pass, item], fail] : [pass, [...fail, item]],5 [[], []]6 );7};// Test array8const nums = [1, 2, 3, 4, 5, 6];// Partition into evens and odds9const [evens, odds] = partition(nums, n => n % 2 === 0);// Print evens: [2, 4, 6]10console.log(evens);// Print odds: [1, 3, 5]11console.log(odds);Output
[ 2, 4, 6 ] [ 1, 3, 5 ]
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
,× 16[× 10]× 10.× 9=× 9(× 7)× 7;× 6>× 3:× 1