-3

I am not so into TypeScript and arrow function and I am searching a smart solution to the following problem.

I have an array of objects like this:

  private events = [
    {id: 1, title: 'All Day Event', start: '2017-02-01'},
    {id: 2, title: 'Long Event', start: '2017-02-07', end: '2017-02-10'},
    {id: 3, title: 'Repeating Event', start: '2017-02-09T16:00:00'},
    {id: 4, title: 'test', start: '2017-02-20T07:00:00'},
  ];

I have to write a method of my class that take the value of the id field and remove this element from the events array.

What could be a smart way to achieve this task?

AndreaNobili
  • 34,200
  • 85
  • 240
  • 456
  • @jonrsharpe no, it seems to me that it is pretty different use case. It delete an element (a number) from an array. I have to delete an object from the array where the id field of this object have a specific value – AndreaNobili Jun 04 '20 at 11:30
  • 1
    So what? The process is still: 1. find the index; and 2. splice it out. Or filter to create a new array without that item. Or look at https://stackoverflow.com/q/34336633/3001761 if you really can't apply that. Either way this is general JS and trivially researched. – jonrsharpe Jun 04 '20 at 11:31

2 Answers2

0

Does this solve your problem? Or I misunderstood your question

 private getNewEvents = (id:number) => { 

          return events.filter(each=>each.id!=id)

       }

Filtering each object of an array and eliminating the object from an array with that passed id.

Dipesh KC
  • 1,516
  • 1
  • 7
  • 12
0

Find the index of your item inside of the array, then splice() it.

const events: { id: number; title: string; start: string; end?: string; }[] = [
    {id: 1, title: 'All Day Event', start: '2017-02-01'},
    {id: 2, title: 'Long Event', start: '2017-02-07', end: '2017-02-10'},
    {id: 3, title: 'Repeating Event', start: '2017-02-09T16:00:00'},
    {id: 4, title: 'test', start: '2017-02-20T07:00:00'},
];

function removeFromEventsById(a_oEvents: { id: number; title: string; start: string; end?: string; }[], a_iIdToRemove: number) {
  const ids: number[] = a_oEvents.map(event => event.id);
  a_oEvents.splice(ids.indexOf(a_iIdToRemove), 1);
  return a_oEvents;
}

console.log(removeFromEventsById(events, 3));

and a little shorter:

function removeFromEventsById(a_oEvents: { id: number; title: string; start: string; end?: string; }[], a_iIdToRemove: number) {
  a_oEvents.splice(a_oEvents.map(event => event.id).indexOf(a_iIdToRemove), 1);
  return a_oEvents;
}
Mike S.
  • 3,050
  • 2
  • 9
  • 23