user3477993
user3477993

Reputation: 213

Array is converted to string while adding elements to it from other array

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.

Upvotes: 5

Views: 44

Answers (4)

Nenad Vracar
Nenad Vracar

Reputation: 122087

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);

Upvotes: 1

zer00ne
zer00ne

Reputation: 44068

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>

Upvotes: 1

Jonathan.Brink
Jonathan.Brink

Reputation: 25423

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

Upvotes: 1

Tim B
Tim B

Reputation: 1983

Try

even.push(arr[i])

instead of

even += arr[i];

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

Upvotes: 3

Related Questions