Home > Blockchain >  Problem with removing rows with .filter JS
Problem with removing rows with .filter JS

Time:05-10

var result_database = [
  { id: 49, absentName: 'man1', absentday: 1 },
  { id: 50, absentName: 'man2', absentday: 1 },
  { id: 49, absentName: 'man1', absentday: 2 },
  { id: 50, absentName: 'man2', absentday: 2 },
  { id: 49, absentName: 'man1', absentday: 3 },
  { id: 51, absentName: 'man3', absentday: 3 },
  { id: 51, absentName: 'man3', absentday: 4 },
  { id: 50, absentName: 'man2', absentday: 3 }
]

So, absent_date and absent_days are to return the current day value, which for monday is 1.

const absent_date = new Date();
const absent_days = absent_date.getDay();

The rest:

let absent_remove = result_database.filter(item => item.absentday != absent_days);
const absent_duplicate = [...new Map(absent_remove.map(item => [item.id, item])).values()]
console.log("Absent Result", absent_duplicate);

So basically, absent_remove removes the database row if the absentday matches absent_days. I then get a bunch of duplicates which I solve with absent_duplicate, removing the duplicates. I'm left with these results down below.

Absent Result [
  { id: 49, absentName: 'man1', absentday: 3 },
  { id: 50, absentName: 'man2', absentday: 3 },
  { id: 51, absentName: 'man3', absentday: 4 }
]

Man1 and Man2 are both absent on monday (1), but they are still in the query, the question is, how do I take them out? The final result should be man3 alone.

CodePudding user response:

Try this:

res = [
  { id: 49, absentName: 'man1', absentday: 1 },
  { id: 50, absentName: 'man2', absentday: 1 },
  { id: 49, absentName: 'man1', absentday: 2 },
  { id: 50, absentName: 'man2', absentday: 2 },
  { id: 49, absentName: 'man1', absentday: 3 },
  { id: 51, absentName: 'man3', absentday: 3 },
  { id: 51, absentName: 'man3', absentday: 4 },
  { id: 50, absentName: 'man2', absentday: 3 }
]

answer = res.filter(x => !res.find(y => x.id == y.id && y.absentday == 1))
console.log(answer)

For every entry in your result we are only keeping it if there are no other entries with an absent day of '1'.

  • Related