Skip to content
Advertisement

I need to find a specific value in an array of arrays. Angular, Typescript

I need to find a value in an array of arrays, but when I use the .find it returns 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 of arrays is datos. And this is the Html:

<p>Subir Archivo excel</p>
<br>

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

<br>

<button (click)="pasardata()">
    Subir a base de datos Firebase
</button>

<br>

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

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


        <button>Enviar</button>

    </form>
</div>

I have tried to access to the datos array of arrays and it returns an empty array, I want to use the array of arrays to display a table an after this get an specific value of the table, using .find().

Advertisement

Answer

Assuming datos: [][] is a nested array of strings, you could use flatMap with find:

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

That being said, if datos is a nested array of objects, you can’t simply compare {} === {}, you would need to compare against some kind of property object:

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

Version without flatMap:

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

Hopefully that helps!

Advertisement