从初始数组中删除与初始数组后面的参数值相同的所有元素

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

本文关键字:数组 元素 删除 参数      更新时间:2023-09-26

有一个初始数组(destroyer函数中的第一个参数),后面跟着一个或多个参数。从初始数组中删除与这些参数具有相同值的所有元素。

这是我的代码,但我无法解决问题。

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],"树",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);
})()

试试这个:

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>

Lodash有一个可能有用的without方法。

链接到文档。

来自lodash文档:

_.不带(array,[values])

使用SameValueZero为创建一个数组,排除所有提供的值平等比较。

示例

_.without([1, 2, 1, 3], 1, 2);
// → [3]

这应该适用于您:

function destroyer(arr) {
    var args = Array.prototype.slice.call(arguments);
    var abc = args.splice(0, 1);
    function des(value) {
        // you don't need loop here, just check if given value is in args array
        return args.indexOf(value) === -1;
    }
    // splice returns array of deleted elements so that your first argument is abc[0]
    return abc[0].filter(des);
}
var result = destroyer([1, 2, 3, 1, 2, 3], 2, 3);
console.log(result);

试试这个简单的代码:

function destroyer(arr) {
  /* Put all arguments in an array using spread operator and remove elements 
     starting from 1 */
  const args = [...arguments].splice(1);
  /* Check whether arguments include elements from an array and return all that 
     do not include(false) */
  return arr.filter(el => !args.includes(el));
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3); // [1, 1]