有一个初始数组(销毁器函数中的第一个参数),后跟一个或多个参数。从初始数组中删除与这些参数具有相同值的所有元素。
这是我的代码,但我无法解决问题。
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);
对于 destroyer(["tree", "hamburger", 53], "tree", 53),代码给出输出 ["hamburger"],工作正常。
但是对于驱逐舰([1, 2, 3, 1, 2, 3], 2, 3);代码没有给出任何输出。
最佳答案
您可以使用Array.filter
。以下示例描述了相同的内容
还有destroyer([1, 2, 3, 1, 2, 3], 2, 3);
在这次通话中,[1, 2, 3, 1, 2, 3]
是第一个参数,2
第二个是 3
是第三。所以 arr 将是 [1, 2, 3, 1, 2, 3]
而不是[1, 2, 3, 1, 2, 3], 2, 3
function removeElementFromArray(arr,num){
var _temp = arr.filter(function(item){
return (item !== num);
});
return _temp;
}
(function main(){
var arr = [1,1,1,2,4,3,2,4,5,4,3,1,4,5,2];
var result = removeElementFromArray(arr,1);
var result1 = removeElementFromArray(arr,3);
console.log(result, result1);
})()
关于javascript - 从初始数组中删除与初始数组后面的参数具有相同值的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34676822/