Skip to content

Instantly share code, notes, and snippets.

@DarrenN
Created November 16, 2012 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DarrenN/4087542 to your computer and use it in GitHub Desktop.
Save DarrenN/4087542 to your computer and use it in GitHub Desktop.
Get even numbers from array using recursion instead of a loop, and without mutating the original array
Array.prototype.evens = function() {
var arr = this;
var out = [];
var count = 0;
var even = function(arr, out) {
if (count <= arr.length - 1) {
if ((arr[count] % 2) === 0) {
out.push(arr[count]);
}
count++;
even(arr, out);
}
};
even(arr, out);
return out;
}
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(a);
console.log(a.evens());
console.log(a);​
@DarrenN
Copy link
Author

DarrenN commented Nov 16, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment