Johnathon64
Johnathon64

Reputation: 1320

javascript not pushing into array

I am looping round a json object and getting an item within the object which holds a comma delimited string, I then split this string and check if its within the array and if not it should push it into the array. The problem is, it never pushes into the array

for (var item = 0; item < rules.length; item++) {
    //we now need to split the item by its delimiter which is a comma ','
    var treeSplit = rules[item].tree.split(',');

    if (treeSplit.length - 1 != childCount) {
        if (isInArray(treeSplit[childCount], aliasGroup)) {
            aliasGroup.push(treeSplit[childCount]);
        }
    } else {
        //do something
    }

This is my isInArray function it takes a value and the array

function isInArray(value, array) {
    return array.indexOf(value) > -1;
}

Upvotes: 0

Views: 64

Answers (1)

Paul
Paul

Reputation: 141839

and if not it should push it into the array

You're missing the not. You're pushing it into the array only if it is already in the array. Add a logical not operator ( ! ) :

if ( ! isInArray(treeSplit[childCount], aliasGroup) ) {
    aliasGroup.push(treeSplit[childCount]);
}

Upvotes: 5

Related Questions