Saving the value of array[i] from a for loop into a fresh array results in undefined

I am currently developing a matching algorithm that compares two arrays of strings. If there is an exact match (===), it stores the results in the unSafeResult array. If there is a match using Regex, it stores the results in the warningResult array. However, when I try to console.log(warningResult), I get the following output:

warning (2) [undefined × 1, "SUGAR.↵CHOCOLATE LIQUOR"]
main.js:41867 warning (3) [undefined × 2, "HYDROGENATED VEGETABLE↵OIL"]
main.js:41867 warning (6) [undefined × 5, "RAPESEED OIL"]
main.js:41867 warning (7) [undefined × 6, "PALM OIL"]
main.js:41867 warning (8) [undefined × 7, "SUNFLOWER OIL"]
main.js:41867 warning (11) [undefined × 10, "RAPESEED OIL"]
main.js:41867 warning (12) [undefined × 11, "PALM OIL"]

When attempting to pass the array to another page, only one element is returned:

[undefined × 11, "PALM OIL"]

Is there a solution to this bug? The expected output should be all elements contained within a single array:

"HYDROGENATED VEGETABLE↵OIL"
"RAPESEED OIL"
"PALM OIL"
"SUNFLOWER OIL"
"RAPESEED OIL"
"PALM OIL"

Below are the relevant code snippets:

matchText(array){        
    for(var i = 0; i < 1; i++) {

        var label = this.labels[i];

        var ingredients = label.description.toString().split(/[(,)]/igm).map(function (ingredients){return ingredients.trim()}, {});

        let ingredientList:string[] = ingredients;
        let ingredientUpdatedList:string[];

        for(var k = 0; k<ingredientList.length; k++){
            if(ingredientList[k] === ""){
                ingredientList = ingredientList.filter((ingredientList) =>{
                    return ingredientList.trim() != '';
                });
            }
        }

        for(var j = 0; j<ingredientList.length; j++){

            let allergy:string[] = ["OIL","SUGAR"];

            var unSafeResult = [];

            for(var e = 0; e<allergy.length; e++) {
                var regexp = new RegExp(allergy[e], "igm");

                if(ingredientList[j] == allergy[e]){
                    unSafeResult[j] = ingredientList[j];   
                    console.log('unSafe',unSafeResult);
                }

                if(ingredientList[j].match(regexp)){
                    this.counter++;
                    var warningResult = [];
                    warningResult[j] = ingredientList[j].valueOf(); //issue here
                    console.log('warning', warningResult);

                }
            }

        }

        if(this.counter >0){
            this.navCtrl.push(UnSafePage,{unSafeResult,warningResult});
        }
        else{
            this.navCtrl.push(SafePage);
        }


    }

Answer №1

Discussing the concept of `undefined`:

When an empty array is defined and a value is assigned to the `array` using an index that is greater than 0, it will automatically be filled with `undefined` values up to the specified index.

To illustrate this, consider the following example:

var testArr = [];

testArr[5] = 'test';

console.log(testArr);

Resolution:

It is recommended to declare the variable warningResult outside of the `for-loop` and then populate it based on other conditions.

var ingredientList = ["HYDROGENATED VEGETABLE↵OIL",
  "RAPESEED OIL",
  "PALM OIL",
  "SUNFLOWER OIL",
  "RAPESEED OIL",
  "PALM OIL"
];

var warningResult = [];

for (var j = 0; j < ingredientList.length; j++) {
  warningResult.push(ingredientList[j].valueOf());
}

console.log('warning', warningResult);

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

Transform an array of strings into its corresponding enum array

One of the challenges I'm facing involves a string array where each item corresponds to an enum case: enum MyEnum { item1, item2, item3, ... } string[] strArray = {"item2", "item3"}; I'm looking for a way to convert strArray fr ...

React Router v6 is throwing an error stating that within the <Routes> component, all children must be either a <Route> or <React.Fragment>

While the code snippet below may have worked perfectly fine in React Router v5, it's causing an error in React Router v6. Error: [Player] is not a <Route> component. All component children of <Routes> must be a <Route> or <React ...

Creating duplicates of form and its fields in AngularJS with cloning

I'm facing an issue with a form that contains various fields and two buttons - one for cloning the entire form and another for cloning just the form fields. I attempted to use ng-repeat, but when I clone the form and then try to clone fields in the or ...

Preventing navigation without using the <Prompt> component in React Router DOM V6

I have recently discovered that in react-router-dom v5, it was possible to utilize the <Prompt> component to prompt the user before a page transition occurs, allowing them to prevent it. However, this feature has been removed in v6 with plans for a m ...

Assistance with utilizing Regular Expressions to extract the className from a React/JSX component

For instance, I have <img className='class' src='somelink' /> and my goal is to extract only the className='class'. I have already attempted using / className='.+'[ |>] while going through files in search of ...

Discover React Native Contacts

I am working on creating a screen page that allows users to navigate through their contact list on mobile phones. I developed a native module to retrieve contact information, which worked well for Android versions 10 and below. However, it stopped functi ...

Creating every potential expression that satisfies a given grammar can be achieved by following these steps

I have developed a grammar for my application that includes the following expressions: (FIND, SEARCH, Lookup) [a, the, an, for] ITEM [in, at] (NEST, SHELF, DESK) The expressions consist of required items in round brackets "()", optional items in square b ...

Classname fails to modify the base style of the AppBar

Struggling to modify the appearance of the AppBar component by utilizing the className attribute, however, the .MuiAppBar-root class consistently takes precedence. const useStyles = makeStyles((theme: Theme) => ({ appBar: { backgroundColor: &apos ...

Populate a form with database information to pre-fill the fields

So I have this web form built with HTML, and there are certain values within the form that can be changed by the user. To ensure these changes are saved, I'm storing them in a database. My goal is to have the form automatically filled with the data fr ...

Looking to include a new item into an array with the help of AngularJS

Having just started with angularJS, I am facing difficulties in adding an object from a form to an array. When I click on "Add New Product", it triggers the "newItemModal". I enter the new product information but the submit button doesn't seem to work ...

Issue with Jquery modal not functioning properly on second attempt

Currently, I am working on developing an application using CodeIgniter. However, I have encountered a problem where the modal window does not open for the second time. Here is a more detailed explanation of the issue: The form (view) in question contains ...

Retrieve the content of the specified element within the webpage

How can I modify the method to successfully retrieve the text content of an element on a webpage using Selenium with JavaScript? Currently, it is returning undefined. homepage.js const { Builder, By, Key, until } = require('selenium-webdriver'); ...

What happens when two style() functions are passed into the query() function for Angular Animations?

As someone who is relatively new to angular animations, I have reviewed the angular.io animation documentation multiple times in order to grasp how everything functions. While I believe I have a decent understanding, there are certain scenarios that the do ...

Firefox not rendering responsive YouTube embed properly

This method of embedding seems to be functioning well on all browsers except for Firefox; I took advantage of a free trial at crossbrowsertesting.com to verify. I’m not using a direct iFrame embed, and all the solutions I’ve come across are related to ...

What are the potential causes of receiving the error message "No Data Received ERR_EMPTY_RESPONSE"?

I often encounter this issue on my website, especially when I have a thread open. It seems to happen whenever I am actively checking for new posts and notifications via Ajax every 10 seconds or so. However, I'm not sure if this continuous reloading is ...

Determining the return type by analyzing the parameter type

I'm currently struggling to find the correct way to define this function in order for all four "tests" that come after it to pass. I've experimented with different function overloads and conditional types, but haven't fully grasped them yet. ...

Issue with CSRF token validation in ASP.NET Core when integrating with Angular

To enhance the security of my application, I decided to implement CSRF-Token protection using Angular documentation as a guide. According to the Angular docs, if a cookie named XSRF-TOKEN is present in the Cookies, it will automatically be included in the ...

Unusual express middleware usage in NodeJS

app.use(function(req,res,next){ console.log('middleware executed'); next(); }); app.get('/1',function(req,res){ console.log('/1'); res.end(); }); app.get('/2',function(req,res){ console.log('/2'); res.end() ...

Issue with Nextjs: getServerSideProps causing a blank page to display instead of redirecting to 404errorCode

I am facing an issue on my dynamic page where the external server returns a 404 error if the requested product is not found. However, when using getServerSideProps, instead of redirecting to a 404 page, it shows a blank page. Below is the code snippet: // ...

Printing directly from a webpage

Can a webpage send a print command without relying on the keyboard shortcut Ctrl + P? I vaguely recall hearing that JavaScript is unable to access the printer directly to initiate a print without using the key combination. ...