In my coding project using Angular and Typescript, I am currently faced with the task of searching for a particular value within

I am facing an issue where I need to locate a value within an array of arrays, but the .find method is returning undefined.

import { Component, OnInit } from '@angular/core';
import * as XLSX from 'xlsx';
import { ExcelSheetsService } from '../services/excel-sheets.service';


@Component({
  selector: 'app-hojaexcel',
  templateUrl: './hojaexcel.component.html',
  styleUrls: ['./hojaexcel.component.css']
})
export class HojaexcelComponent implements OnInit {

  
  constructor( private excelsheetService: ExcelSheetsService ) { }

  ngOnInit(): void {
  }


  codigo: any = ''; 
  datos: [][] = [];
  

  onFileChange( evt: any  ){

  
    
  const target: DataTransfer = <DataTransfer> (evt.target);

  if(target.files.length !== 1) throw new Error ('No se pueden subir varios archivos a la vez');

  const reader: FileReader = new FileReader();

  reader.onload = ( e: any ) => {
    const bstr: string = e.target.result;

    const wb: XLSX.WorkBook = XLSX.read( bstr, { type: 'binary' } );

    const wsname: string = wb.SheetNames[0];

    const ws: XLSX.WorkSheet = wb.Sheets[wsname];

    this.datos = (XLSX.utils.sheet_to_json(ws, { header: 1 }));
    console.log(this.datos);

    return this.datos;

  }; 

  reader.readAsBinaryString(target.files[0]);

  }

  look(): any{
    
    const found = this.datos.find(element => element == this.codigo );
    console.log(found);
    console.log(this.datos);
    

  }


  


  pasardata(){
    this.excelsheetService.impData( this.datos )
      .subscribe( resp => {
        console.log(resp);
      });

  }



  

}

The array containing arrays is referred to as datos. Below is the HTML:

<p>Upload Excel File</p>
<br>

<input type="file" (change)="onFileChange($event)" multiple="false" />

<br>

<button (click)="pasardata()">
    Upload to Firebase Database
</button>

<br>

<div class="col">
    <form (ngSubmit)="look()">

        <input type="text" placeholder="Code" name="codigo" [(ngModel)]="codigo"/>


        <button>Send</button>

    </form>
</div>

I have attempted to access the datos array of arrays and it returns an empty array. My goal is to utilize the array of arrays to display a table and then retrieve a specific value from the table using the .find() method.

Answer №1

To work with a nested array of strings labeled as datos: [][], you can employ the combination of flatMap and find:

const found = this.datos
  .flatMap(element => element) // unravels nested arrays
  .find(element => element === this.codigo);

If your datos is a nested array consisting of objects, direct comparison like {} === {} won't suffice. You'll have to compare it based on a specific property:

const found = this.datos
  .flatMap(element => element) // unravels nested arrays
  .find(element => element.someProperty === this.codigo);

An alternate version without using flatMap:

const found = this.datos
  .reduce((acc, curr) => acc.concat(curr))
  .find(element => element === this.codigo);

I trust that clears things up!

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

Using Typescript to set the image source from a pipe

I've been working on creating a custom pipe similar to the code below: @Pipe({ name: 'imagePipe' }) @Injectable() export class ImagePipe { constructor(public someService: SomeService, public storage: Storage) { } transform(value: ...

Save the text entered into an input field into a Python variable

Is there a way to retrieve the text from input fields that do not have a value attribute using Selenium? The issue is that these fields are populated automatically, possibly through JavaScript, upon page load and the text does not appear in the HTML source ...

What is the process for updating npm and node version on Windows operating system?

Currently immersed in a finance project, but embarking on a new one where we are facing a node version issue. Any tips on how to avoid this problem? ...

method that provides route-specific variable outputs

I have a situation where multiple routes require the same userdata from the database. Although I have a function to verify if the user is logged in, this function does not return the user variables. Here is an example route: app.get('/template', ...

Puppeteer patiently waits for the keyboard.type function to complete typing a lengthy text

Currently, I am utilizing puppeteer for extracting information from a particular website. There is only one straightforward issue with the code snippet below: await page.keyboard.type(data) await page.click(buttonSelector) The initial line involves typin ...

Enhance your data presentation with Angular Material tables featuring multiple sources

I am currently facing an issue with my table that is being used to display multiple sets of data. The problem I'm encountering is that while the data is showing up correctly, the paginator and sort functions are not working as intended. The sorting ...

PHP Combining two arrays by adding an element to each existing element

How can I merge elements from one array with each element in another array? For instance: $colors = array("black", "white", "yellow"); $numbers = array("1", "2", "3"); I am looking to create a new array that combines them all like so: $colornumber = a ...

Facing difficulty in uploading image to local server using Froala editor

For testing purposes, I've been attempting to upload images using the Froala WYSIWYG editor on my localhost, but unfortunately, it's not functioning as expected. After selecting an image to upload, it briefly appears faded in the editor and then ...

What is the best way to replace multiple strings with bold formatting in JavaScript without losing the previous bolded text?

function boldKeywords(inputString, keywords){ for (var i = 0; i < keywords.length; i++) { var key = keywords[i]; if (key) inputString= inputString.replace(new RegExp(key, 'gi'), '<strong>' + ...

Error Alert: LocalStorage is undefined in this context - NextJS

Having trouble retrieving access and refresh tokens from local storage. Each attempt results in a 500: Internal Server Error, with an error indicating LocalStorage is undefined. Research suggests that LocalStorage may not be compatible with rendering with ...

There was an error with validation in Graphql that was of an undefined type

Running a gql query on a React app with default variables is causing an error. The specific error message is: Error: GraphQL error: Validation error of type FieldUndefined: Field 'firstname' in type 'HealthcareWorkersPage' is undefin ...

Observable emitting individual characters instead of the entire string in an optional parameter of an activated route

Within an Angular component, I have a method with the following content: this.route.paramMap.pipe( switchMap((params: ParamMap) => { let fooValue = params.get('selectedid'); console.log("inside switch map with value as " + ...

Display conceal class following successful ajax response

Upon clicking the button, the following script is executed: $.ajax({ url: "<?php echo CHILD_URL; ?>/takeaway-orders.php", type: 'POST', async:false, data: 'uniq='+encodeURIComponent(uniq)+'&menu_id=' ...

Angular Typed Forms Cannot Assign Values to Incomplete Types

I have created a simple example to demonstrate the goal I am trying to achieve: In essence, there are two types defined as follows: type BaseType = FormGroup<{ user: FormControl<string>; }>; type SomeOtherType = FormGroup<{ user: FormC ...

Getting a boolean response from an asynchronous SQLite query in Express

I am currently developing a middleware that verifies the validity of a session (meaning it has a logged-in user attached). For this purpose, I am utilizing sqlite3 for node.js. Since I am not very familiar with JavaScript, I am facing some challenges figu ...

Tips for adjusting the order in which styles load in NuxtJS

I need to adjust the loading order of styles in my current project. In my custom stylesheet style.css, I've made some overrides, body { font-family: "Lato", sans-serif; font-size: 14px; font-weight: 400; font-style: normal; ...

When attempting to redirect to the home page in Angular 6, the page successfully redirects but fails to load properly

I am new to using angular. Recently, I converted a large project from html/css/php/js to twig/slim, and switched the hosting platform from apache2/sql to s3 buckets/lambda apis. While I have successfully converted smaller projects to angular without any i ...

Having trouble accessing the application on localhost

I'm diving into the world of Docker! I'm looking to build a personalized docker image for an Angular application using a Dockerfile. I've successfully created the image and got the container up and running, but unfortunately, I'm unable ...

Updating Hidden Field Value to JSON Format Using jQuery and JavaScript

var jsonData = [{"Id":40,"Action":null,"Card":"0484"}]; $('#hidJson', window.parent.document).val(jsonData); alert($('#hidJson', window.parent.document).val()); // displays [object Object] alert($('#hidJson', window.parent.doc ...

Hover over a ListItem

Looking for advice on how to incorporate a Mouseover feature into a Material UI ListItem from the following link: http://www.material-ui.com/#/components/list. As the "SecondaryText" is limited to 2 lines, I am exploring options to display additional data ...