JohnDoe99
JohnDoe99

Reputation: 109

I need to write a function that loops through an array of numbers, and returns the odd & even numbers in it's array.

I need to write a function that loops through an array of numbers, and returns the odd & even numbers in it's array.

I'm not sure if there's a better way to do this, and I'm stuck. Is there a way to return both statements?

var myNums = [1, 2, 3, 4, 5, 6, 7, 9];

var evens = []; 
var odds = [];  

function oddsAndEvens(nums) {
	for(var i = 0; i < nums.length; i++){
      if(nums[i] % 2 === 0){
        evens.push(nums[i])
      }
      else if (!nums[i] % 2 === 0) {
		odds.push(nums[i])
      }
    }  
      console.log(evens);
      console.log(odds);
    //I need it to "return" the array,
    //not console log
      
}
  
console.log(oddsAndEvens(myNums));

Upvotes: 0

Views: 123

Answers (4)

Eli Richardson
Eli Richardson

Reputation: 930

A clean function to separate the evens from the odds.

function arrangeNums(array) {
  let odd = array.filter(i=>i%2!==0);
  let even = array.filter(i=>i%2===0);
  return {even:even,odd:odd};
}
console.log(arrangeNums([...Array(100).keys()]));

Upvotes: 1

Ananthakrishnan Baji
Ananthakrishnan Baji

Reputation: 1290

Off course you can, just return an object containing both evens and odds,

    function oddsAndEvens(nums) 
    {
      var evens = [];
      var odds = [];
      for(var i = 0; i < nums.length; i++){
          if(nums[i] % 2 === 0){
            evens.push(nums[i])
          }
          else if (!nums[i] % 2 === 0) {
    		    odds.push(nums[i])
          }
        }  
        return {"evens":evens,"odds":odds};   
    }
      
    var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
    result = oddsAndEvens(myNums);
    console.log(result.evens);
    console.log(result.odds);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

You could use an object for the result and taken an array for the keys of the object to push the value.

function getGrouped(array) {
    return array.reduce(function (r, a) {
        r[['even', 'odd'][a % 2]].push(a);
        return r;
    }, { odd: [], even: [] });
}

var myNums = [1, 2, 3, 4, 5, 6, 7, 9];

console.log(getGrouped(myNums));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 0

Long Phan
Long Phan

Reputation: 338

return arrays instead of console.log should work

var myNums = [1, 2, 3, 4, 5, 6, 7, 9];

var evens = []; 
var odds = [];  

function oddsAndEvens(nums) {
	for(var i = 0; i < nums.length; i++){
      if(nums[i] % 2 === 0){
        evens.push(nums[i])
      }
      else if (!nums[i] % 2 === 0) {
		odds.push(nums[i])
      }
    }  
    
     // return array of values you want
     return [evens, odds] 
}
  
console.log(oddsAndEvens(myNums));

Upvotes: 0

Related Questions