Tobias Glaus
Tobias Glaus

Reputation: 3628

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.

Upvotes: 1

Views: 94

Answers (5)

Vadimz
Vadimz

Reputation: 371

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.

Upvotes: 0

余俊浩
余俊浩

Reputation: 26

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.

Upvotes: 0

ellipsis
ellipsis

Reputation: 12152

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)

Upvotes: 4

arizafar
arizafar

Reputation: 3122

If you are not rigid to create an array and is not going to be used anywhere else in your code then no need to.

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

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()));

Upvotes: 1

Related Questions