Skip to content

Instantly share code, notes, and snippets.

@minedun6
Created May 13, 2019 21:59
Show Gist options
  • Save minedun6/cdfb2e6e9d86419be285233084953cd9 to your computer and use it in GitHub Desktop.
Save minedun6/cdfb2e6e9d86419be285233084953cd9 to your computer and use it in GitHub Desktop.
Split an Array based on callback
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