Skip to content

Instantly share code, notes, and snippets.

@krohne
Last active August 29, 2015 14:12
Show Gist options
  • Save krohne/ab0579f09e4cb214fda6 to your computer and use it in GitHub Desktop.
Save krohne/ab0579f09e4cb214fda6 to your computer and use it in GitHub Desktop.
From an array of integers (negative and positive), return the even integers, without looping or using Array API calls
function getIntegers() {
// Go to the source for true random numbers
// Fetch 10 integers from -100 to 100
var xmlHttp = new XMLHttpRequest(),
randomUrl = "http://www.random.org/integer-sets/?sets=1&num=10&min=-100&max=100&commas=on&order=index&format=plain&rnd=new";
xmlHttp.open("GET", randomUrl, false);
xmlHttp.send();
return xmlHttp.responseText.split(", "); // convert to an array
}
var integers = getIntegers();
// Shortcut: even integers always end in 0,2,4,6,8
// Thanks to regxr.com for helping me work out the correct regex
var evens = integers.join().match(/(-?[1-9]*\d*[02468])(?=\D)/g);
console.log("Integers:", integers);
console.log("Even integers:", evens);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment