0

I am trying to take an array of numbers and log what numbers are modulus 2 with a remainder of 0 i % 2 === 0. For the numbers that are modulus 2 with a remainder of 1 i % 2 === 1, I want to push those numbers to an array (seemed like the best fit to log a set of numbers).

From there I would return the sumTotal of the numbers that are %2 === 0 and print which numbers in the array were %2 === 1.

The problem below works for the if statement but when I added in my else if I am having trouble figuring out how to push items into the array in the else if statement.

var numSet = [1, 4, 6, 450, 5, 222, 397, 962, 678, 222, 459];

var myFunc = function (num) {
    var total = 0;
    var total2 = [];
    for (var i = 0; i < num.length; i += 1) {
        if (num[i] % 2 === 0) {
            total += num[i];
        } else if (num[i] % 2 === 1) {
            total2[num[i]] = num[i].push;
       console.log(total2);
        }   
    } 
    return 'The total is ' + total + ' and the remainder is ' + total2;
};
2
  • 2
    The line you want is total2.push(num[i]) Commented Dec 29, 2013 at 3:18
  • @tymeJV that worked, thanks. How would I add in a space between each number when it runs the return statement? as now each number has a comma but no space so its not as clean to read? Commented Dec 29, 2013 at 3:29

1 Answer 1

2

The problem with your code is that, you can push the new values into total2 like this

total2.push(num[i]);

But you can use Array.filter and Array.reduce, like this

var numSet = [1, 4, 6, 450, 5, 222, 397, 962, 678, 222, 459];

var oddNumbers = numSet.filter(function(currentNumber) {
    return currentNumber % 2 === 1;
});

var total = numSet.reduce(function (total, currentNumber) {
    if (currentNumber % 2 === 0) {
        total += currentNumber;
    }
    return total;
}, 0);

console.log(total, oddNumbers);

Output

2544 [ 1, 5, 397, 459 ]
Sign up to request clarification or add additional context in comments.

4 Comments

It should be noted that Array.filter and Array.reduce do not work in IE8 and below. I also believe he wanted the array to contain the odd numbers and the total of the even numbers.
why cant I push the way @tymeJV said? I tried it and it worked. Guessing something bigger may be going on that I am missing.
@jstone That was my first suggestion too... :)
Ah gotcha now. Thanks for the clarification.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.