VueJS .filter unexpectedly alters array data

My goal is to filter an array based on the contents of another array, and here is the code I have written for it.

private get filteredArray() {
  const filteredArray = this.unfilteredArray;
  console.log(this.unfilteredArray);

  filteredArray = this.unfilteredArray.filter(
    (p) => this.filteredNumbers.includes(p)
  );
  return filteredArray;
}

For example, let's say we have two arrays with the following values:

this.unfilteredarray = ["1", "2", "4", "3"]
this.filteredNumbers = ["2"]

The this.filteredNumbers array contains values selected by the user from a multiple selection box. In this case, the user has selected 2, and as a result, the function returns an array filteredArray containing the value "2". However, if the user selects another number such that this.filteredNumbers becomes ["2", "3"], the function still only returns "2" in filteredArray instead of both 2 and 3. This issue arises because upon logging, it is observed that after selecting a new filterNumber for the second time, the unfilteredArray only retains the value "2" instead of all its original numbers 1-4. What am I missing here or should I approach this differently?

EDIT: Follow-up question regarding the correct solution If I have an object containing three different arrays that I want to filter simultaneously and then return the object with its filtered arrays intact, how can I achieve that? The code snippet below attempts to do so, but it doesn't work as it alters the original arrays. Would I need to create three separate methods for each array?

private get filteredObject() {
   this.object.unfilteredArray.filter(
    (p) => this.filteredNumbers.includes(p)
  );
   this.object.unfilteredArrayTwo.filter(
    (p) => this.filteredNumbers.includes(p)
  );
   this.object.unfilteredArrayThree.filter(
    (p) => this.filteredNumbers.includes(p)
  );
  return object;
}

Answer №1

When you use

const filteredArray = this.unfilteredArray;
, it doesn't actually create a clone of the array, but rather makes a reference to it. This means that if you modify filteredArray, you are also modifying this.unfilteredArray because they both point to the same data.

To avoid this issue, you can return a new filtered array by creating a temporary one like so:

private get filteredArray() {
   return this.unfilteredArray.filter(
    (p) => this.filteredNumbers.includes(p)
  );
}

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

Storing array elements in a MySQL database through PHP and jQuery

Hello, I am in the process of populating a table by inserting multiple rows individually for each query. Here is the code snippet that shows how I am sending an array elements: The HTML markup: <form action="post.php" method="POST"> <h1>U ...

Set up webpack on your Mac using npm

Seeking help to install webpack using npm: sudo npm install -g webpack The following error message is encountered: node-pre-gyp WARN Using needle for node-pre-gyp https download node-pre-gyp WARN Pre-built binaries not installable for <a href="/cdn- ...

Center column with header and footer flanking each side

Trying to replicate the layout of the Facebook Android app on my page. The app features a 3 column design, with the central column exclusively displaying the header (no footer included, although I require one for my version). This visual representation is ...

Calculate the Total Amount using Jquery

Fiddle <table border="1" class="cssTable"> <tr id="trGroup"> <td> Black, Total <asp:Label ID="lblCount" runat="server"></asp:Label> </td> </tr> <tr> <td cla ...

Unable to properly call a JavaScript file from an HTML file

Executing this simple code with the JavaScript line placed under Script tags will trigger the desired alert message: <!DOCTYPE html> <!-- saved from url=(0014)about:internet --> <html> <body> <script type="text/javascript" > ...

Every time $injector.get is invoked, it triggers the run() method of the Angular module

I find myself in a situation where I need to manually retrieve objects from the Angular $injector. Up until now, I have been using the following approach: var injector = angular.injector(['app.service', 'ng']); var myService = injecto ...

Implementing pagination links to trigger image changes on click

I have a javascript function that swaps the image source when clicked. I am looking to incorporate pagination links in this script. Specifically, I want to include "Previous" and "Next" text links to navigate between images. Can someone help me figure out ...

EJS: display length when this condition is met

Imagine a scenario where there is a MySQL database connected to NodeJS and EJS. The database contains three categories: OK, WARNING, and FALSE. How can the total count of each category be obtained from the database? An attempt was made by implementing th ...

Refreshing the page using AJAX in WooCommerce after executing my custom script

I am experiencing an issue with WooCommerce. I am trying to incorporate a custom jQuery script that executes after clicking the add to cart button. When I do not include my script, everything functions properly - the AJAX request triggers and the product i ...

Apply a custom filter to ng-repeat results

Asking for advice on how to iterate over an array using ng-repeat and filter the contained objects based on a function property. Find more details in this Plunker link. Let's say we have an object like this: vm.show1 = function(){ return true; }; ...

Developing a specialized directive to enhance bootstrap menuItems

I have created a custom directive in AngularJS for the navbar in Bootstrap. This directive uses ng-transclude and handles two types of list items (li) depending on whether it is a dropdown or not. However, I am experiencing issues with the dropdown functio ...

Enhance your Next.js routing by appending to a slug/url using the <Link> component

In my Next.js project, I have organized my files in a folder-based structure like this: /dashboard/[appid]/users/[userid]/user_info.tsx When using href={"user_info"} with the built-in Next.js component on a user page, I expect the URL to dynamic ...

Replicate and customize identical object for creating instances in JavaScript

I am working with an object that has the following structure: var customObject = function() { this.property = "value"; }; customObject.prototype = new otherObject(); customObject.prototype.property2 = function() {}; This is just a snippet as the ac ...

I am utilizing React to pull data from the database with a one-day discrepancy in the backend

Despite trying numerous solutions, I am still puzzled as to why this issue persists. For instance, in my database, there is a date listed under the "date_of_birth" column as 2023-12-29. However, when examining my backend code, it displays as "date_of_birth ...

The click detection on loaded 3DObjects using threejs raycast is not functioning properly

After loading a .obj file using the following code: var loader = new THREE.OBJMTLLoader(); loader.load( "../obj/machine.obj", '../obj/machine.mtl', this.loadObject); I attempt to detect a click on it with the following code: click: function( ...

Calculating the sum of values in a specific position within an array of Javascript

Here is an array that needs to be updated: let arr = [ { "Id": 0, "Name": "Product 1", "Price": 10 }, { "Id": 0, "Name": "Product 1", "Price": 15 } ] I am looking for a way to add 1 to all the Price values, resulting in: let Final_arr = [ { ...

MongoDB Client > Error: No operations provided - cannot proceed

NPM Library: "mongodb": "3.1.4" Encountering an issue while attempting to bulk insert a list of data: Here is the code snippet: db.collection('products').insertManyAsync(products, {ordered: false}) The error message displayed: An Invalid O ...

Python/Numpy/Boolean Indexing: Update boolean array by replacing consecutive stretches of True values with N consecutive True values

Suppose you have a numpy boolean array arr = np.array([1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1]) You want to identify the positions where there are at least n consecutive true values (from left to right). For n = 2: # True 2x (or more) in a row # ...

Learn how to implement Bootstrap 4's select styling to customize dropdown links, such as using it for a tags

My goal is to apply Bootstrap 4 form styling, like form-control and custom-select, to actual links (dropdown a tag). For example: <select class="custom-select" onchange="location = this.value;"> <option selected>Cho ...

What distinguishes res.send from app.post?

I'm just starting to learn about express and HTTP. I've heard that the express library has app.get, app.post, and res.send methods. From what I gather, app.get is used for GET requests and app.post is used for POST requests. How does res.send fit ...