Satch3000 Satch3000 - 7 months ago 17
Javascript Question

Javascript Remove data from array function

I have an array and here's how it looks:

{id:"1", videotype:"youtube", videoId:"y685gVGRQ98"},{id:"2", videotype:"youtube", videoId:"CtjuDJytD18"}


Each entry has an Id.

I need a function to remove all entries belonging to the chosen Id.

for example:

removeFromArray(2);

It would then remove all this: id:"2", videotype:"youtube", videoId:"CtjuDJytD18"

Answer

My question is...How do I do to remove a specific entry?

You can write another method

removeDataToArray: function(id, videotype, videoId) {
       var videoArray = JSON.parse(document.getElementById("videoLinksArray").innerHTML);
       //filter out item that matches the id, videoType and videoId
       videoArray = videoArray.filter( function(val){
          return !( val.id == id && val.videoType == videoType && val.videoId == videoId );
       });
       document.getElementById("videoLinksArray").innerHTML = JSON.stringify( videoArray );
},

It would be more like: removeDataFromArray(id) and it would know the unique id of the entry

Then the filter will change to

       videoArray = videoArray.filter( function(val){
          return val.id != id;
       });

Edit

removeFromArray(2);

It would then remove all this: id:"2", videotype:"youtube", videoId:"CtjuDJytD18"

removeDataToArray: function(id) {
       var videoArray = JSON.parse(document.getElementById("videoLinksArray").innerHTML);
       //filter out item that match the id
       videoArray = videoArray.filter( function(val){
          return val.id != String( id ) ;
       });
       document.getElementById("videoLinksArray").innerHTML = JSON.stringify( videoArray );
},