Search code examples
javascriptarguments

How to remove elements from an array using arguments object - what's wrong with my code?


I am trying to remove elements from an array that is passed on a function as an argument. The elements that I am trying to remove from the array are the ones equal to the following arguments of the function. Like this: destroyer([1, 2, 3, 1, 2, 3], 2, 3); so if the array (first argument of destroyer) contains "2" and "3", I want them removed. So calling the function should return [1, 1].

function destroyer(arr) {

  var args = [];

  for(var j = 1; j<arguments.length; j++){

      args.push(arguments[j]);

    for(var i = 0; i<arr.length; i++){

        if(args.indexOf(arr[i]) > -1){

            arr.splice(i, 1)
        }
    }
  }
  return arr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

I don't understand why my code works for destroyer([1, 2, 3, 1, 2, 3], 2, 3); (it returns [1, 1]) but not for destroyer([2, 3, 2, 3], 2, 3); (it should return [], but returns [3]).

Please, help me understand why this doesn't work.

I have created a repl.it at https://repl.it/BTu5


Solution

  • the privous answer is right, but i got something working , it's more similar to the question's code, help him to understand: code:

     function destroyer(arr) {
    
     var args = [];
      //You want add all the nums you want remove from array, so you start from 1, which means second arg,first arg is the array you want to perform
      for(var j = 1; j<arguments.length; j++){ 
      //You store the args to an arg array
          args.push(arguments[j]);
        //Once you have the arg, you want loop the target array, see if the newly added arg exist in the target array, if it is, then remove it
        for(var i = 0; i<arr.length; i++){
            //Found it, remove it now! note: your found the index, then you need take it out, check the doc for slice function arr.slice([begin[, end]]) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
            if(args.indexOf(arr[i]) > -1){
                //key change, remove the element 
                arr.splice(i, i+1)
               }
           }
       }
      return arr;
      }
     destroyer([2, 3, 2, 3], 2, 3);
    

    `

    Also, have created a play for you

    https://repl.it/BTu5/5

    example: slice(1,4) extracts the second element up to the fourth element (elements indexed 1, 2, and 3).