learningjavascriptks
learningjavascriptks

Reputation: 325

my for loop not is not executing?

this is an assignment in free code camp, my problem is my for loop is not iterating, it's a function returned from filter method, i need to loop through the extra parameters aside from the initial array[0] to compare if it match and remove.

the result of this code is 1,3,1,3 which i want to be 1,1.

function destroyer(arr) {
    var p = arguments.length; // arr  length
    var r = arguments; // 
    function argScope(item) {
        debugger;
        for(var a =1; a<=p; a++) { // start iterate at 1, 0 is the initial array I want to remove elements
            if(item == r[a]) { // this is true at 1 so 2 is removed, but loop doesn't execute
                return false;
            } else {
                return item;
            }
        }
    }

    var v = arr.filter(function(item,index,array) {
    debugger;
    return argScope(item); // call a function for the scope

    });
    return v;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3); // function call

help?

Upvotes: 0

Views: 65

Answers (2)

user5734311
user5734311

Reputation:

This should do it:

function destroyer(arr) {

  function argScope(item) {
    debugger;
    for (var a = 1; a < arr.length; a++)
      if (item == arr[a]) return false;
    return true;
  }

  return arr[0].filter(function(item) {
    debugger;
    return argScope(item); // call a function for the scope
  });
}

var myArray = [1, 2, 3, 1, 2, 3];
var filteredArray = destroyer([myArray, 2, 3]);

console.log(filteredArray);

Upvotes: 0

Alexey Soshin
Alexey Soshin

Reputation: 17691

You return from your loop after exactly one iteration. Maybe you meant:

for(var a =1; a<=p; a++) { // start iterate at 1, 0 is the initial array I want to remove elements
    if(item == r[a]) { // r and a is not set, value is only set after 
        return item;
    }
}
return false;

Upvotes: 3

Related Questions