Dominic Dominic - 2 years ago 80
Javascript Question

I'm only able to return 1 array

I'm trying to take this array and split it into 2 new arrays, evens and odds and return them. When I run the code below I am only getting the odds, why is that? And what can I do to solve it?

Thanks in advance.

var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];

function divider( arr ) {
var evens = [];
var odds = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
} else {
return(evens, odds);


Answer Source

Because JavaScript can only return one value. Ever.

return(evens, odds)

evaluates to the same value as

return odds

due to the comma operator wrapped in grouping parenthesis.

Perhaps returning an array of arrays (or even an object of arrays) is useful..

return [evens, odds]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download