Destroyer function help

function destroyer(arr){
    let len = arguments.length;
    let arry = [];
    for(let i = 1;i< len;i++){
       arry.push(arguments[i])
    }
    for(let x =0;x<arr.length;x++){
        for(let j=0;j<arry.length;j++){
            if(arr[x] == arry[j]){
                arr.splice(arr.indexOf(arry[j]),1);
            }
        }
    }
    
   console.log(arr);
};

So, this function takes an array followed by some extra arguments. This function delete items in this array which has some value of those extra arguments.

destroyer([3, 5, 1, 2, 2], 2, 3, 5);
result is [1,2];

this function should delete all 2,3,5 in this array . But I don’t know why it didn’t delete last 2 . Please someone help me is there anything I am missing?

Try looping backwards through the array instead.

1 Like

I would avoid loops and use Array.prototype.filter which lets you selectively remove items from an array that don’t pass a test.

In your case:

function destroyer(arr, ...rest){
  return arr.filter(item => rest.indexOf(item) < 0);
}

console.log(destroyer([3, 5, 1, 2, 2], 2, 3, 5));
// [ 1 ]

console.log(destroyer([1, 2, 3, 4, 5], 1, 5));
// [ 2, 3, 4 ]
1 Like

That’s a good idea! Though, instead of using <0 I would explicitly use === -1 to more clearly call out the not found situation.

2 Likes

Yup, fair point :slight_smile:

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.