Uzma Khan Uzma Khan - 1 year ago 46
Javascript Question

Remove all elements from the initial array that are of the same value as the arguments followed by the intial array

There is an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.

Here is my code,but I am unable to solve the problem.

function destroyer(arr) {
// First I have converted the whole input into an array including the arguments
var args = Array.prototype.slice.call(arguments);
var abc=args.splice(0,1);//Here I have taken out the array part i.e[1,2,3,1,2,3] and also now args contain 2,3 only

function des(abc){
for(var i=0;i<abc.length;i++){//I tried to check it for whole length of abc array
if(args.indexOf(abc)===-1){
return true; //This should return elements of [1,2,3,1,2,3] which are not equal to 2,3 i.e [1,1] but for string inputs it is working correctly.How to do for these numbers?
}
}
}
return arr.filter(des); //but this filter function is returning empty.How to solve my problem??
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);


For destroyer(["tree", "hamburger", 53], "tree", 53) the code is giving output ["hamburger"],which is working fine.

But for destroyer([1, 2, 3, 1, 2, 3], 2, 3); code is giving no output.

Answer Source

Try this:

function destroyer(arr) {
    var args = Array.prototype.slice.call(arguments, 1);

    function des(abc){
        return args.indexOf(abc) === -1;
    }
    return arr.filter(des);
}
var result = destroyer([1, 2, 3, 1, 2, 3], 2, 3);
document.getElementById('output').innerHTML = JSON.stringify(result);
<pre id="output"></pre>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download