Created
May 13, 2019 21:59
-
-
Save minedun6/cdfb2e6e9d86419be285233084953cd9 to your computer and use it in GitHub Desktop.
Split an Array based on callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.partition = function(predicate) { | |
const results = [[], []]; | |
this.forEach((item, index) => { | |
results[predicate(item, index) ? 0 : 1].push(item); | |
}); | |
return results; | |
}; | |
const [evens, odds] = [1, 2, 3, 4, 5].partition(n => n % 2 == 0); | |
console.log(evens); // [2, 4] | |
console.log(odds); // [1, 3, 5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment