Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
      evens.push(arr[i]);
    } else {
      odds.push(arr[i]);
    }
  }
  return(evens, odds);
}

divider(numbersArray);
like image 228
Dominic Avatar asked Nov 29 '22 23:11

Dominic


2 Answers

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]
like image 129
user2864740 Avatar answered Dec 04 '22 09:12

user2864740


You should return your results as an array.

return [evens, odds];

And then to access the results:

var evens;
var odds;

var arrayResults = divider(numbersArray);
evens = arrayResults[0];
odds = arrayResults[1];
console.log(evens);
console.log(odds);
like image 21
user212514 Avatar answered Dec 04 '22 11:12

user212514