Ensuring the Persistence of Array Manipulations in JavaScript Functions

I've been working on a JavaScript function in ES5 that is designed to take an array, filter it, and then assign the original array with the filtered results.

If you'd like to check out my progress so far, feel free to visit my plunk here.

Here is a rough outline of what I'm attempting to achieve:

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 suspect that the issue lies within how arrays are referenced. If anyone has any insights on how to tackle this problem, I would greatly appreciate it.

Answer №1

Make sure to update the array with the changes and store it in a variable called result:

function removeEntry(inputData, result) {
  return result.filter(function(entry) {
    return entry.date !== inputData.date;
  });
}

result = removeEntry(inputData, result);

Answer №2

When using Array.filter, it's important to note that it returns a new array instance. This means that when you assign the result of filter back to itself (e.g. result = result.filter(...)), you lose the reference to your original array. A better alternative in this case would be to 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);

Answer №3

If you want to replace all elements in an array based on a certain condition, you can utilize the Array#splice method.

function replaceEntries(data, result) {
    Array.prototype.splice.apply(result, [0, result.length].concat(result.filter(function(item) {
        return item.date !== data.date;
    })));
}

var result = [{ date: '20171116' }, { date: '20171115' }],
    data = { date: '20171116' };
    
replaceEntries(data, result);
console.log(result);

In ES6:

function replaceEntries(data, result) {
    var temp = result.filter(item => item.date !== data.date);
    result.length = 0;
    result.push(...temp);
}

var result = [{ date: '20171116' }, { date: '20171115' }],
    data = { date: '20171116' };
    
replaceEntries(data, result);
console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hiding the style tag in the head section of a Laravel-Vue.js application with Vue.js

Currently, I am working on a Laravel-Vue.js application. I have noticed that when Vue.js renders CSS, it appends some style tags in the HTML head as shown in the image below. Is there a way to hide these tags? My initial thought is that it can be achieved ...

Having trouble making an ajax request using Cordova?

I recently started a new project and included some code for making a request. Below is how my JavaScript file looks: (function () { "use strict"; document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false ); function onDeviceR ...

How can I incorporate "Context" into route configuration?

I am facing an issue with adding the searchContext context in my App.js file to provide access to variables in my Navbar and Results components. Despite trying various approaches, I have been unsuccessful so far. Here is the code snippet: <Router> ...

Determine the size of a multidimensional array in C using the scanf

I'm currently facing a challenge with using multidimensional arrays for a specific program. The program involves using scanf to extract a user ID and a string of characters from a redirected file. The file format consists of a three-digit user ID foll ...

Utilizing Python with Selenium to address the "ElementNotVisibleException" by employing the "execute_script" method

I'm currently using Selenium to capture the content of a webpage. The issue is that the content on the page changes when certain checkboxes are clicked. My goal is to click a checkbox and then save the updated page content, but these checkboxes are co ...

What causes the z-index value to stay the same even after it has been modified using the .css() function?

The z-index property defaults to auto, as explained in the MDN documentation. Despite setting the z-index to 1 using the following code: $("body").css("z-index", 1); Upon retrieving the value of z-index with this code: $("body").css("z-index"); The re ...

Is it possible to align an image that uses position:relative with one that uses position:absolute?

On a webpage, I have placed two images. The first image is set to position:relative and the second image is positioned right below it with position:absolute. How can I ensure that as you zoom in or out, the second image remains aligned with the first ima ...

Searching for specific values within a multidimensional array using PHP

I need to create a PHP page that can show the BackupJobs from the past week. The backup-jobs are fetched from an API and stored in JSON format. I am encountering an issue when I have a specific BackupSetID and want to display all corresponding BackupJobs ...

Executing ws.send from the controller in a Node.js environment

In my project, I am looking to send a websocket using express-ws from a different controller rather than through a route. In my server.js file, I have the following code: var SocketController = require('./routes/ws.routes'); var app = express(); ...

dynamic array within a large matrix

I am tasked with creating a large matrix (specifically 10,000x10,000) with the backbone as an array of float pointers: typedef float* DynamicMatrix[MAT_SIZE]; DynamicMatrix matDyn; Next, I need to allocate rows and set them to zero. // allocate rows a ...

What is the best way to switch between two components using vue.js?

I have a scenario where I need to toggle between two components, Register.vue [`my_reg-page`] and Login.vue [`my-signin_page`]. If the user opens the register page in the browser (using the /register URL), clicking on the Login heading will toggle the user ...

What is the best way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

What is the best way to use JavaScript to locate and interact with a button on a webpage based on its XPath and the text it contains?

Is it possible to find a specific element by the text it contains using only JavaScript? While in Selenium we can easily locate elements based on their text content, for instance: the_element = browser.find_element_by_xpath("//span[contains(.,TEXT)]") In ...

Tips for efficiently submitting data to multiple child components without causing unnecessary re-renders

In my React project, I am encountering a challenge with submitting data that is spread across multiple children components. The project involves developing a recipe app where the parent component, RecipeCreator, renders various child components tasked with ...

NodeJS Issue: Failure to Save Record in Parse

Here is my code snippet to save data into a table. let Parse = require('parse').Parse; export const gameInsert = async (data) => { try { const game = Parse.Object.extend('Table'); const query = new game(); dat ...

Yearly Grouping with MongoDB's Aggregate Framework

I've been experimenting with the aggregate function to group date fields by year: db.identities.aggregate([ { $group : { _id : { year : {$year : "$birth_date"}}, total : {$sum : 1} } } ]) However, I encountered a c ...

data retrieval not refreshing sorting post construction

My challenge involves fetching data from MongoDB with sorting. While it works perfectly on the development server, it fails to update the data after being built and hosted. import Review from "@/models/review"; import connectdb from "@/util/ ...

Sending form data to the server using JavaScript: A step-by-step guide

Currently, I am dealing with the configuration of two servers. One server is running on React at address http://localhost:3000/contact, while the other is powered by Express at address http://localhost:5000/. My goal is to transmit form data as an object v ...

Exploring the insights into React-hook-form Controller

I've inherited a website project that utilizes an unfamiliar method in the Controller part of react-hook-form. Here is an example of the code snippet: const CheckboxController = (props: CheckboxProps) => { return ( <Wrapper> < ...

The Google analytics page tracking feature is experiencing issues within an AngularJS application and is not functioning correctly

My current project focuses on AngularJS, catering to both mobile applications and desktop websites. I have downloaded analytics.js locally and integrated it into my GA tracking code within the index.html file: (function(i,s,o,g,r,a,m){i['GoogleAnalyt ...