Searching with RegEx results in a negative value, despite the fact that the specified phrase is clearly within the array

When importing an excel file into Angular using the xlsx library, the file is converted into an object of arrays. Each array represents a row from the excel file, and each item within the array corresponds to a cell in that row. The process for importing the excel file is as follows:

onFileChange(event: any) 
  {
    const inputFile: DataTransfer = <DataTransfer>(event.target); 
    const fileReader: FileReader = new FileReader();
    fileReader.onload = (event: any) => 
    {
      const binaryString: string = event.target.result;
      const workBook: XLSX.WorkBook = XLSX.read(binaryString, { type: 'binary', sheetStubs: true}); 

      const workSheetName: string = workBook.SheetNames[0];
      const workSheet: XLSX.WorkSheet = workBook.Sheets[workSheetName];

      this.data = <Array>(XLSX.utils.sheet_to_json(workSheet, 
      {header: 1, blankrows: true }));


    };

A Regex search is then used to find the column containing a manufacturer description by looping through each array and looking for the term cap:

getManufacturerDescriptionColumn()
  {
    console.log(this.data)
    for (const row in this.data)
    {

      var manDescriptIndex = row.search(/cap/i)
      console.log(manDescriptIndex)
      if (manDescriptIndex > -1) 
      {
       return manDescriptIndex
      }
    }
  }

Despite the clear presence of the phrase "cap" in some arrays, all values returned are -1, indicating that the phrase is not found. See the example below where CAP appears in several rows but still returns -1 values.

https://i.sstatic.net/I2z2w.png

This issue persists even when attempting to iterate at a deeper level to isolate the individual cells' strings within the rows.

Answer №1

It is evident from the documentation on MDN that using the loop for..in is incorrect in this scenario. The appropriate loop to use would be for..of. Further explanation provided below

for..in is intended for iterating over objects, but it can also work with arrays by providing you with the indexes (e.g., 0, 1, 2, etc.)

To access the values directly, utilize the for..of loop as recommended in the MDN documentation

If you log console.log(row) before proceeding with the check, this distinction will become more apparent

Answer №2

After reviewing @AlejandroVales's answer, I must admit he was right on point. However, I have an update to the solution that might be helpful for those facing a similar issue. Instead of simply changing in to of, I took a different approach by using regular expressions to verify each element in the arrays. By thinking outside the box, I was able to find a more effective solution. Here's a snippet of the code:

var cap = new RegExp(/cap/i)
    for (const row of this.data)
    {
      for (let cell = 0; cell<row.length; cell++)
      {
        if (cap.test(row[cell]))
        {
          return cell
        }
      }
    }

This code sets a variable as a regex, then iterates through each cell in each array (where each array represents a row in an excel document). By identifying the cell that returns a TRUE value, the problem is solved. If my explanation is unclear, feel free to leave a comment below. I may not be an expert, but I strive to contribute value to this community that has given me so much in the past.

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

Contrasting createMuiTheme and getMuiTheme

When would you choose to use one over the other? What are the key differences in how they operate? ...

What is the best method for importing OrbitControls into my three.js project?

I'm having trouble importing OrbitControls into my project. I included three.js and then attempted to import OrbitControls, but it's not functioning as expected. I added three.js to the HTML body using the following command: script src="https:/ ...

Switch the Points from squares to rectangles

I have a unique art piece made up of particles that are currently squares. I would like to transform them into rectangles. I am aware that non-uniform scaling is not supported for points, but I am seeking advice on how to achieve this desired effect. Belo ...

What is the best way to reference a dynamic ID in JavaScript when clicking for an action on a different

Here is my HTML code snippet: <table> <tr> <td> @Html.DropDownList("Statues", (SelectList)ViewBag.UserType, string.Empty, new { @class = "NewIDCn",@id = "name1" }) </td> <td> ...

Having difficulty parsing the text into individual components found within the Feature modules

In my Shared module, I have a component that requires localization using NGX-TRANSLATE. However, it seems like the component in the shared module is not able to access the JSON file loaded in app.module.ts, resulting in the error: "Cannot read property &ap ...

Issue with hardhat failing to detect balance transfer from smart contract

I am currently in the process of creating tests for a smart contract that I have developed. Below is a simplified version of the smart contract: Please Note: I have hard-coded the value to ensure accuracy regarding the amount leaving the contract. functio ...

What are the steps to implement templates in Angular 2?

I've been experimenting with templates in Angular2, but I'm not getting the expected results. Here's what I've tried so far. Does anyone have any suggestions or perhaps a different approach I could take? To begin with, I'm using t ...

The resolution error has occurred: { Issue: Module 'npm-watch' not found

After successfully running "npm install" and installing all packages in the node_module folder, I encountered errors when running the "npm start" command in the command prompt. D:\INSM-HTML-Player>npm start <a href="/cdn-cgi/l/email-protection" ...

The attempt to run 'setProperty' on 'CSSStyleDeclaration' was unsuccessful as these styles are precalculated, rendering the 'opacity' property unchangeable

I am attempting to change the value of a property in my pseudo element CSS class using a JavaScript file. Unfortunately, I keep encountering the error mentioned in the title. Is there any other method that can be used to achieve this? CSS Code: .list { ...

What is the best way to limit a slash command to only be accessible to those with specific roles on a Discord server?

I am currently working on a discord bot using Discord.js V14 and implementing a command called "claimticket". However, I am facing an issue where I need to restrict this command to only members who possess one of the two specific roles that I have mentione ...

Angular 4: Unidirectional data flow from View to Component

Struggling to secure user credentials in my Angular form due to 2-way data binding displaying encrypted values within the component. Here's the code snippet: <form> <div class="input-group"> <span class="input-group-a ...

Tips for invoking a URL in an Ajax JSON request

Having trouble calling a webservice from a specific directory within my project. The URL I'm trying to access is "~/RA/WebServiceRAOpen.asmx/OpenedRAlistByBranch" but it's not functioning as expected. $.ajax({ url: "~/RA/WebServiceRAOpe ...

Issues persist with AngularJS integration using Modernizr

Incorporating AngularJS and Modernizr, I aim to identify media queries and trigger a function whenever the window or viewport is resized. My goal is to control element visibility based on whether the user is on a desktop or mobile device - certain elements ...

Executing a task on a deconstructed item within a JavaScript object

function transformTitle (string) { return string.charAt(0).toUpperCase() + string.slice(1) } Looking to capitalize the title directly after destructuring in a single line. const { question } = this.props const { title, Question_uuid: questionUUID } ...

In Perl, attempting to use the reference "HASH(0x13bd718)" as an array index can lead to unexpected results

Working on a Perl script to create the 2048 game for practice, I keep encountering an error that looks like this: An issue with using reference "HASH(0x13bd718)" as array index at line 181 in 2048.pl, line 11. The problematic code revolves around a subro ...

What is the best way to restrict users from accessing more than 5 Bootstrap Tab-Panes at once?

Users are restricted to opening only a maximum of 5 tab panes, even if there are multiple tab buttons available. If the user tries to click on the 6th tab, an alert message will be displayed. function addTab(title, url){ var tabs=$(".tabs"), tab ...

Enable tabber upon clicking on the navigation bar

Hello there, I am facing an issue with my website's navigation. I have a navigation bar with the unique id #nav and I want to activate a specific tab based on the clicked navigation list item. The HTML structure of the navigation #nav looks like this: ...

Troubleshooting IE Freezing Issue Due to JavaScript Code with .addClass and .removeClass

Need some help troubleshooting why my code is causing IE to crash. After commenting out sections, I discovered that the issue arises when using .addClass and/or .removeClass inside the if conditions: if ( percentExpenses > 50 && percentExpenses ...

What is the best way to increase the value of a 3d numpy array?

If I have a 3D array (3x3x1) as shown below: [[[149] [121] [189]] [[ 32] [225] [ 44]] [[ 33] [133] [ 11]]] How can I expand all values so that they are the same in the innermost dimension (3x3x3) like this: [[[149 149 149] [121 121 121] ...

I am wondering why the content is not showing up when using state.map(foo => <>{foo}</>) in my code

Why does the first tsx code display the state.map properly while the second code displays nothing? Despite both pieces of code performing the same task in the same way, one list is correctly displayed while the other state.map has never rendered anything, ...