过滤阵列中的数组

问题描述 投票:1回答:1

我正在做一个FreeCodeCamp挑战,“寻找和破坏”我创建一个从提供的数组中删除元素的函数。

特定

function destroyer(arr) {
// Remove all the values
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

结果应该是

[1, 1]

虽然我已经看到了各种解决方案,但如果我能够制定解决方案,我就是这么想的,因为我对我很直观,希望能让我更好地理解过滤。我认为我的解决方案不起作用的原因是因为我没有正确使用该方法。

filter();

无论如何,这是我的尝试:

function destroyer(arr) {
// Remove all the values
var args = Array.prototype.slice.call(arguments);
//makes the arguments an array

function destroy(value) {


for (var i=1; i < args.length; i++) 
return value !==args[i];
// creates a loop that filters all arguments after the first one and removes from the initial argument, regardless of how many there are. 

}

var filtered = arr.filter(destroy);
return arr[0];
}


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

我注意到了

var filtered = arr.filter(destroy);

可能是问题,因为最初的三个参数正在被过滤,但不是第一个参数。但是,如果我尝试做的话

var filtered = arr [0] .filter(destroy);我认为这将针对第一个参数,抛出错误。有可能以这种方式解决问题吗?我想这样做是因为我喜欢以下功能的设置方式:

function badValues(val){  
 return val !== 2;   
}

function bouncer(arr) {
  return arr.filter(badValues);  
}

bouncer([1, null, NaN, 2, undefined]);

并希望用2代替需要删除的参数。

感谢大家!

javascript arrays filter arguments
1个回答
0
投票

This是一个工作的例子,如果你想自己发现解决方案,不要阅读它,如果你真的想解决这个并学习,你需要read如何filter工作。你很亲密

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

  var filtered = arr.filter(destroy);  

  // you must return the filtered array
  return filtered;

  function destroy(value) {    
    for (var i=1; i < args.length; i++){

      // you must return false if you find it so filter removes the value
      if (value === args[i]) return false;
    }

    // if you loop through all and don't find it, return true so filter keeps the value
    return true;
  }
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);
© www.soinside.com 2019 - 2024. All rights reserved.