Skip to content

Instantly share code, notes, and snippets.

@rproenza86
Last active January 4, 2017 20:49
Show Gist options
  • Save rproenza86/61a0d14a29089a5b4a73ddc1200223f5 to your computer and use it in GitHub Desktop.
Save rproenza86/61a0d14a29089a5b4a73ddc1200223f5 to your computer and use it in GitHub Desktop.
/**
Code Challenge Needed:
Using Javascript, given an array of n integers (example: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 112, 113] ), remove all odd numbers, leaving only the even numbers.
Rules:
NO LOOPING. This means native methods, or libraries that loop for you are not allowed either.
Supply the answer on github via Gist
**/
var numbersArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 112, 113];
//initial array
console.log('The original numbers array was : ', numbersArray);
//this code is just one more variation( looping with a for... I know :) ) but despite the polemic about performace this kind of solutions are more clear, more maintainable and reusable code also are more easy to trace
function getEvens(array){
let position = 0,
arrayLength = array.length;
for (var i = 0; i < arrayLength; i++) {
if ( !(array[i] % 2) ) {
array[position++] = array[i];
}
}
array.length = position;
return array;
}
var evensArray = getEvens(numbersArray);
//final array
console.log('The evens numbers are : ', evensArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment