Something with a G
Something with a G

Reputation: 5

Fill array in a for loop

I'm trying to fill a new array within a loop, but I can't figure it out.

What I need is, that I filter all value's from my temporary array to set to my new array. all value's that start with "+" need to get into the array "my_hash_plus". this is what I have now.

var my_hash_plus = new Array;   
$.each(my_hash_plus_tmp, function(_, temp) {
    if (tmp[0] == "+") {
        my_hash_plus[] = temp;
    }
});

I noticed that I can't fill my array with [] in js, but if I those things then my_hash_plus becomes a normal var... So my question is: what is the best way to get all the value's from the array my_hash_plus_tmp that start with "+" into a new array (which I will call my_hash_plus)

Upvotes: 0

Views: 216

Answers (1)

adeneo
adeneo

Reputation: 318182

Use push()

var my_hash_plus = [];   

$.each(my_hash_plus_tmp, function(_, temp) {
    if (temp.charAt(0) == "+") {
        my_hash_plus.push( temp );
    }
});

In newer browser you can do it pretty easily without jQuery as well

var my_hash_plus = my_hash_plus_tmp.filter(function(it){return it.charAt(0)=='+'});

Upvotes: 4

Related Questions