vturkovic
vturkovic

Reputation: 137

Javascript function to remove specific element from array based on two conditions / two properties

How to remove element from array based on two values?
E.g. element with day: 8, date: august 2021.'

Array:

var events = 
  [ { day:  8, date: 'july 2021.'   } 
  , { day: 16, date: 'july 2021.'   } 
  , { day:  8, date: 'august 2021.' } 
  , { day: 16, date: 'august 2021.' } 
  ] 

e.g. if I click on day 8, august I want to remove just element
8, august not also 8, july

What I tried:

// number of the day clicked $scope.newEvent (8)
// date of day clicked $scope.selectedDate ("august 2021.")

var newEventsArray = events.filter(e => 
  e.day != $scope.newEvent && e.date == $scope.selectedDate)

Upvotes: 0

Views: 85

Answers (2)

Juno
Juno

Reputation: 41

Im, expecting you are printing the button using

events.map((item, id) => <Item />)

if thats the case you have access to item id, and you can delete the exact item using id

Upvotes: 1

fravolt
fravolt

Reputation: 3001

You're almost there already, it's a bit of a logic error. Say we write the day being equal as D, and the month/year being equal as M.

You now filter out all of them such that

!D & M

Meaning if D=8 and M=August, you would filter out all dates for which the day is is not equal to 8, and for which the month is equal to August.

What you want, is to remove the entry only when the day and the month are equal to the values, that is

D & M

Now of course, using this as a filter would yield only 8, August, so you want to invert it

!(D & M)
!D | !M

In other words, you should change your expression to the following:

var newEventsArray = events.filter(e => e.day !== $scope.newEvent || e.date !== $scope.selectedDate)

Upvotes: 2

Related Questions