简体   繁体   中英

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

 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.

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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