简体   繁体   English

使用forEach过滤数组

[英]Filter array using forEach

I got an array of dates, where I want to filter out specific days. 我有一系列日期,我想在其中过滤掉特定的日子。 That's my previous solution, which works fine: 那是我以前的解决方案,效果很好:

var available = dates.filter(function(e) {
  return (
    e.getDay() != 0 && // sunday
    e.getDay() != 6 && // saturday
    e.getDay() != 2 && // tuesday
    e.getDay() != 3 && // wednesday
  );
});

Now, I want to make this dynamic. 现在,我想使其动态化。 So I got an array like this: 所以我得到了一个像这样的数组:

var unavailable = [0, 2, 3, 6]

And then I try to filter out those days like this: 然后,我尝试像这样过滤掉那些日子:

unavailable.forEach(function(x){
  available = dates.filter(function(e, index){
    return e.getDay() != x;
  });
});

That doesn't appear to be working tho. 这似乎不起作用。 What did I do wrong and how can I get this to work? 我做错了什么,如何使它起作用? Thanks in advance. 提前致谢。

No need to use forEach use filter and includes 无需使用forEach使用filterincludes

 var unavailable = [0, 2, 3, 6] var dates = ['1-1-2019', '1-2-2019', '1-3-2019', '1-4-2019',' 1-5-2019', '1-6-2019', '1-7-2019', '1-8-2019',' 1-9-2019']; workingDays = dates.filter(e => { return !unavailable.includes(new Date(e).getDate())}) console.log(workingDays) 

You need to swith the order of comparing and return the result of the check. 您需要切换比较顺序并返回检查结果。 In this case you need Array#every instead of Array#forEach , because you need a result for the filtering. 在这种情况下,您需要Array#every而不是Array#forEach ,因为您需要过滤结果。

available = dates.filter(function(e, index) {
    return unavailable.every(function(x) {
        return e.getDay() != x;
    });
});

The same with Array#some and a negation of the returned result and a negated comparison. Array#some相同,返回结果取反,比较结果取反。

available = dates.filter(function(e, index) {
    return !unavailable.some(function(x) {
        return e.getDay() === x;
    });
});

A shorter approach. 一种较短的方法。

var unavailable = [0, 2, 3, 6]
    available = dates.filter(e => !unavailable.includes(e.getDay()));

I got the right answer for you. 我为您找到了正确的答案。

let unavailable = [0, 2, 3, 6];
available = dates.filter(e => !unavailable.includes(e.getDay());

The problem with your code is that for each element in unavailable array, you are resetting available . 代码的问题在于,对于不可用数组中的每个元素,您都将其重置为可用

You can try the following: 您可以尝试以下方法:

available = dates.filter(function(e) {
  return unavailable.indexOf(e.getDay()) === -1 ? true : false;
})

The problem with your code is that forEach rewrites the value of available every iteration, and your program adds difficulty to understand. 您的代码的问题在于forEach重写每次迭代的可用值,并且您的程序会增加理解的难度。

如果您不拘泥于创建数组,并且不打算在代码中的其他任何地方使用它,则无需这样做。

 dates.filter(e => e.getDay().toString().match(/0|6|2|3/)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM