Getting the even values of an array in JavaScript without using any loops

November 15, 2012

At R/GA Buenos Aires we have an strict hiring process, specially for Open Standard Developers (frontend developers). One of the very first questions that we ask in our technical interviews is how to get the even numbers of an array using JS. Obviously, if you can't answer that extremely basic question we assume that you won't be able to tackle more complex problems.

Most people use a variation of the following code:

var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    b = [];

for (var i = 0; i < a.length; ++i) { 
    if ((a[i] % 2) === 0) {
        b.push(a[i]);
    }
}

// "b" will now hold all the even values of "a"

However, I thought that it'd be interesting to challenge some of my co-workers to solve a variation of this extremely basic problem but this time without using for, while or Array.forEach. As an example I provided them with the following code:

var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

a.filter(function(a) { return (a & 1) === 0; });

Additionally, I thought that this was an interesting challenge, so I asked the same question on Twitter. These are the responses that I received:

// Code by @hughfdjackson
a.reduce(function(arr, num) { 
    if (num % 2 == 0) arr.push(num); 
    return arr; 
}, []);
// Code by @29a_ch
a.toString().replace(/,?\d+[13579]/g, '').split(','); 
// Code by @tomasdev
var b = [];

a.sort(function(c,d) {
    if ((c & 1) < (d & 1)) {
        b.push(c);
    }
});

if (!(a[a.length - 1] & 1)) {
    b.push(a[a.length - 1]);
}
// Code by Mike Roufa
function popall(arr, onpop) {
    var val = arr.pop(); 
    
    onpop(val); 
	
    if (arr.length > 0) popall(arr, onpop); 
}

var coll = [];
popall(a, function(v) { if (v % 2 === 0) coll.push(v); });
// coll now contains all the even numbers.
// Code by @sergiokuba
var myNiceLittleArray = a, 
    result = []; 

setTimeout(function arrrgh() { 
    var value = myNiceLittleArray.pop(); 
    if (value % 2 === 0) { 
        result.push(value); 
    } 
   
    if (myNiceLittleArray.length) { 
        setTimeout(arrrgh, 0); 
    } 
}, 0);

// Code by @brunolazzaro 
a.join().match(/\w?(\d+)*[24680]/g);

Do you know any others? Post them in the comments below!

HINT! Other possible methods may include using recursive functions or the callback parameters of regex functions ;)