I am trying to write a JavaScript function (ES5) that will take in an array, filter it, and set the original array to the new one.
Here is my plunk: https://plnkr.co/edit/OWeOjJ3SLVGYRaweyy3Z
Here is the basic pseudocode of what I am trying to do:
var result = [{ 'date': '20171116' }, { 'date': '20171115' }];
var data = { 'date': '2017116' };
deleteEntry(data, result);
console.log(result); //should have one entry
function deleteEntry(data, result) {
result = result.filter(function(item) {
return item.date !== data.date;
});
}
I believe the issue is to do with array references. I am not sure how to accomplish the task.
Array.filter returns a new array instance so you loose the reference of your original array when you do result = result.filter(...). You can use array.splice instead:
var result = [{ 'date': '20171116' }, { 'date': '20171115' }];
var data = { 'date': '20171116' };
deleteEntry(data, result);
function deleteEntry(data, result) {
var index = result.findIndex(item => item.date === data.date);
result.splice(index, 1);
}
console.log(result);