0

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;
}
5
  • 1
    have you logged or debugged in the developers console? Commented Jan 11, 2016 at 15:00
  • Try console logging the treesplit variable to see if it has split the json object as you were expecting. It may be that the split isn't working as expected. Commented Jan 11, 2016 at 15:01
  • so I stuck a breakpoint in firebug on the isInArray line and it doesn't seem to want to go into the code inside that if statement Commented Jan 11, 2016 at 15:01
  • @Vistari It has split properly so I have a string hello,world it splits into an array held in treeSplit childCount is set to 0 Commented Jan 11, 2016 at 15:02
  • Ah your if statement is incorrect when you're checking if it's in the array. You should negate it using ! so that it will work as expected. Commented Jan 11, 2016 at 15:03

1 Answer 1

5

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]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

You beat me to it. I just noticed it when I was copying the code for further inspection. +1'ed

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.