Fatih Can
Fatih Can

Reputation: 479

Filter objects with matching given date string

I have an array of objects which contain taskname, createdAt fields...

I get next week days by moment js and I want to get next weeks tasks.

I have tried the code down below but it gives error:

Expected an assignment or function call and instead saw an expression

const nextWeekDays = (key: string): any => {
switch (key) {
  case 'week-next':
    const startNextWeek = moment().add(1, 'weeks').startOf('isoWeek');
    const endNextWeek = moment().add(1, 'weeks').endOf('isoWeek');
    let date: string[] = [];

    for (
      var m = moment(startNextWeek);
      m.isBefore(endNextWeek);
      m.add(1, 'days')
    ) {
      date.push(m.format('DD-MM-YYYY'));
    }

    return date;

Code where I want to get tasks length:

 case 'week-next':
    let dates = veri("week-next")
    return props.dealspaceTaskList.filter(
      dt => dates.includes((t:any) => {t == dt.createdAt})
    ).length;

Upvotes: 1

Views: 100

Answers (1)

ghybs
ghybs

Reputation: 53185

The syntax for Array.prototype.includes is myArray.includes(searchElement), it does not take a function argument (unless the array is actually a list of functions, in which case you would search by function reference).

So in your case, TypeScript points out this discrepancy:

let dates = ["01-02-2022", "02-02-2022"]

const result = [{
    createdAt: "03-02-2022"
}, {
    createdAt: "04-02-2022"
}].filter(
    dt => dates.includes((t: any) => { t == dt.createdAt }) // Error: Argument of type '(t: any) => void' is not assignable to parameter of type 'string'.
    //                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
).length;

You just need to pass the value, not in function form:

const result2 = [{
    createdAt: "03-02-2022"
}, {
    createdAt: "04-02-2022"
}].filter(
    dt => dates.includes(dt.createdAt) // Okay
).length;

Playground Link

Upvotes: 1

Related Questions