Holger Kibur
Holger Kibur

Reputation: 47

Javascript hasher nested function

I am trying to create a function that will trim off array values that are not 4 chars long. For some reason, it does not work. I think that it might be with the return statement but I am not sure and I need help with it. Here is the code for the function: (Please don't suggest ways of making the hasher better, I just need help on the function)

function cutit(seq){
        for(var i=0;i<seq.length;i++){
            var temparr=seq[i].split("");
            if(temparr.length % 4 !== 0){
                seq.splice(seq[i],1);
                return seq;
            }
        }
    }

Upvotes: 0

Views: 32

Answers (1)

Bergi
Bergi

Reputation: 665456

Five things:

  • Yes, the return should happen after the loop not after the first found item to delete.
  • .splice() takes an index for the first parameter, not the element. Pass i instead of seq[i].
  • splice(…, 1) does decrease the length of the array you're iterating over by one. You need to take care of that and decrease your counter as well to have a look at the i index again, where on the next iteration the next element will sit.
  • Instead of splitting the string into an array of single chars and taking the length of that, just take the length of the string directly.
  • Your functions removes all strings that are not a multiple of 4 long, not all that are not exactly 4 characters long. Not sure whether that is intended.

function cutit(seq) {
    for (var i=0; i<seq.length; i++) {
        if (seq[i].length !== 4) {
            seq.splice(i--, 1);
        }
    }
    return seq;
}

Also, notice that mutating an array is seldom a good idea (especially in an inefficient way like this with multiple splices). Returning a new array is so much easier, and you can use the higher-order filter Array method for that:

function cutit(seq) {
    return seq.filter(function(str) {
        return str.length === 4;
    });
}

Upvotes: 1

Related Questions