5

I'm at the start of the road so bear with me. The issue is presented in the title.The code i'm using is as followed:

var arr = [7, 29, 8, 33, 37, 4, -31, 39, 32, -12, 9];
var even = [];
for (var i = 0; i < arr.length; i++){
        if(arr[i]%2 == 0){
            even += arr[i];
        }
    }
console.log(even.length);

The code should just get the even elements from an array and move it to another. When the code is ran, the variable "even" will hold the elements as "8432" instead of [8, 4, 32], which will give me a wrong result in console at the end: "4" instead of "3". I can't figure it out why would behave like this.

4 Answers 4

3

Try

even.push(arr[i])

instead of

even += arr[i];

See http://www.w3schools.com/jsref/jsref_push.asp for more example

Sign up to request clarification or add additional context in comments.

Comments

1

Use push rather than +=:

even.push(arr[i]);

In JavaScript you can kind of think of arrays as a stack (pushing and popping).

More information

Comments

1

Store your evens in a variable then push that value into the even array. Try the Snippet, it'll display the results.

SNIPPET

var arr = [7, 29, 8, 33, 37, 4, -31, 39, 32, -12, 9];
var even = [];
for (var i = 0; i < arr.length; i++){
        if(arr[i]%2 == 0){
            var x = arr[i];
            even.push(x)
        }
    }
console.log(even);
<!-- Results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Comments

1

You can use filter() method

var arr = [7, 29, 8, 33, 37, 4, -31, 39, 32, -12, 9];
var even = arr.filter(function(el) {
  return el % 2 == 0;
});

console.log(even);

Comments

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.