Sift through JavaScript problems

My goal is to implement a filtering function on my input that will display a different result. However, I have encountered an issue where the this.data.stationInfo.stations array is being changed, as shown in the console.log output. According to the Mozilla docs, the filter should create a new array instead of modifying the existing one. I suspect that the problem lies with how I am using this. Does anyone have any ideas on how to resolve this?

onTextChanged: function () {
            let copy = this.data.stationInfo.stations;
            console.log("this.data.stationInfo.stations.length", this.data.stationInfo.stations.length);
            copy  = copy
                .filter(el => {
                    return el.eng站名.toLowerCase().startsWith(this.data.searchBar.search.toLowerCase())
                    ||
                        el.站名.toLowerCase().startsWith(this.data.searchBar.search.toLowerCase())
                    ||
                        el.traWebsiteCode.startsWith(this.data.searchBar.search.toLowerCase())
                });
            this.data.resultDetails.stations = copy;
            console.log("copy.length", copy.length);
            console.log("after copy.length this.data.stationInfo.stations.length", this.data.stationInfo.stations.length);
        },

console.log output:

JS: 'this.data.stationInfo.stations.length' 239

JS: 'copy.length' 4

JS: 'after copy.length this.data.stationInfo.stations.length' 4

JS: 'this.data.stationInfo.stations.length' 4

JS: 'copy.length' 0

JS: 'after copy.length this.data.stationInfo.stations.length' 0

JS: 'this.data.stationInfo.stations.length' 0

JS: 'copy.length' 0

JS: 'after copy.length this.data.stationInfo.stations.length' 0

JS: 'this.data.stationInfo.stations.length' 0

JS: 'copy.length' 0

JS: 'after copy.length this.data.stationInfo.stations.length' 0

UPDATE:

Check out the NativeScript PlayGround example here:

Answer №1

It is not recommended to create references. By setting a reference to your original array, any changes made to the copy will also reflect on the original array.

onTextChanged: function () {
            console.log("this.data.stationInfo.stations.length", this.data.stationInfo.stations.length);
            let newArray  = this.data.stationInfo.stations
                .filter(el => {
                    return el.eng站名.toLowerCase().startsWith(this.data.searchBar.search.toLowerCase())
                    ||
                        el.站名.toLowerCase().startsWith(this.data.searchBar.search.toLowerCase())
                    ||
                        el.traWebsiteCode.startsWith(this.data.searchBar.search.toLowerCase())
                });
            this.data.resultDetails.stations = newArray;
            console.log("copy.length", copy.length);
            console.log("after copy.length this.data.stationInfo.stations.length", this.data.stationInfo.stations.length);
        }

Instead, I recommend optimizing your code by performing all necessary actions in one place. You can iterate over the array and directly exclude unwanted stations. Here's an example:

onTextChanged: function () {
const stations = this.data.stationInfo.stations;
function doSearch(el,str) {
    return 
        el.eng站名.toLowerCase().startsWith(str) ||
        el.站名.toLowerCase().startsWith(str) ||
        el.traWebsiteCode.startsWith(str);
}

for(let j=0; j < stations.length; j++){
    if(!doSearch(stations[j], this.data.searchBar.search.toLowerCase())){
        stations.splice(j, 1);
    }
}

console.log(stations);
}

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

The best practices for managing item spacing in React or React Native

I am facing some challenges while trying to adjust the spacing of my components. My goal is to have the grid occupy 90% of the screen, with the gear icon taking up the remaining 10% <View style={{ paddingLeft: insets.left, padding ...

Rendering a Component Inside Another Component

I am facing a situation where I have a component named TicketView being used within another component called Table. The initialization of TicketView in the table looks like this: <TableRow key={index}> ... <TableRowColumn style={{width: & ...

Solution to trigger CSS :hover to refresh following a transition (such as expanding a menu)

While there are existing discussions on this topic, I am presenting my query for two specific reasons: It introduces a potential alternative solution The demo code could be helpful to individuals looking to emulate a menu Following a CSS transition, the ...

The instance is referencing "firstName" during render, but it has not been defined as a property or method

I am encountering a persistent warning message related to the inputs on my Signup.vue page. This warning is appearing for all four input fields in my code: firstName lastName email password The warning mentioning specific instances keeps popping up consi ...

The element.find() function in Angular struggles to locate input elements nested within other elements

I have been working on a directive that has the following template (simplified): <table> <tr> <td> <input type="text"/> </td> <td> <inpu ...

Experiencing a failure in defining the factory

I'm currently working on passing data between controllers in Ionic with Angular. I know that using a factory is the best approach for this, but I keep encountering an error: ReferenceError: setData is not defined This is my code: app.factory("Pla ...

Are there any alternative methods to define a constructor function in TypeScript that do not involve utilizing classes? Upon researching on this subject, it appears that all sources suggest using classes

Is it possible to transform this class declaration into a constructor function without losing TypeScript compatibility? class Animal { constructor(public name: string, public energy: string) {} } ...

Tips on using Visual Studio Code to troubleshoot Angular 4 unit tests

I am working on an Angular 4 project with Material design in Visual Studio Code. The setup is done using angular/cli. Currently, I have been writing unit tests using Karma and Jasmine. However, when trying to debug the tests by setting breakpoints, it doe ...

Can you show me how to use jQuery/JS to split this string into two separate arrays?

Can you help me separate this string into two arrays? { array1: [ 'mary', 'steve', 'george' ], array2: [ 'dog', 'cat', 'hobbit' ] } I attempted the following code but encountered a syntax err ...

Sharing information among v-for divisions - Vue.js

I am currently delving into the world of VueJS. While my code may not be the most elegant, it does the job almost as intended. The issue I am facing is that the API provides the title and href separately in different v-for loops, even though each loop only ...

"Enhance Your Website with Javascript: Combining and Incorpor

I'm struggling to assign the selected attribute to the option value that is already rendered within the object. However, despite the values being equal, the selected attribute is not being added. Could this issue be related to the appending process? ...

Unable to perform queries from a separate file as connection.query function is not recognized

Currently diving into node.js and databases. Attempting a mysql query, but encountering the error TypeError: connection.query is not a function. Utilizing Node MySQL 2 (https://www.npmjs.com/package/mysql2) package; The connection and queries in app.js f ...

Ways to rotate SVG images exclusively upon clicking

After experimenting with rotating SVG images on my navbar buttons, I encountered an issue. Whenever I click one button, all the images rotate simultaneously. Additionally, clicking elsewhere does not reset the images to their original positions. This is t ...

Rendering JSON Data in JavaScript using Table Pagination

Currently, I am working on rendering JSON data from a URL onto a table. My challenge is to display only 10 rows per page and I'm seeking guidance on how to achieve this. Below is the code snippet that I am using for rendering the data: const url = " ...

Is it possible to refresh a tree without having to reload the entire webpage?

I'm currently developing a web application utilizing zTree library. The tree structure is populated with data retrieved from a Golang backend server. Each leaf node in the tree should have custom icons that can change dynamically while the application ...

Provide input to npm when running "my command" and utilize that input within my functions

Consider the contents of app.js const { doCoolStuff } = require("./api/myApi"); // grab parameter from command line and store it in "myParam" doCoolStuff(myParam); ... // more code And Package.json: { "name": "------ ...

Create Joi Schema based on TypeScript types/interfaces

Searching for a way to convert Typescript types or interfaces into joi schema objects led me to various solutions that did the opposite, such as generating Typescript types/interfaces from joi schemas. I came across options like ts-interface-builder and ts ...

Button Triggering Javascript

Looking for a handy solution that allows users to either accept or reject a website's cookie policy. I came across an interesting library called cookies-EU-Banner (found at ) which seems to be quite popular. It recognizes when the user clicks on Reje ...

In React, the constant always has a default value of "Object : Default"

My current project involves using SlateJS and I am encountering an issue when trying to load data into a const using: imgData = data.get("file"); Everything works as expected if React is not imported, but once it is included, the object contains unexpecte ...

Switching the active className in React and Next.js based on selection status

My goal is to dynamically change the className of each Card component when clicked on. When one Card is selected, the others should revert back to their default className. This is my UserBookingData component: const UserBookingData = ({ bookings }: any) = ...