learningjavascriptks learningjavascriptks - 3 months ago 7
Javascript Question

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?

Answer

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);

Comments