Created
November 16, 2012 13:58
-
-
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
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.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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fiddle: http://jsfiddle.net/darren_n/uXt8S/