Search in Javascript array

Asked

Viewed 30 times

-2

Good afternoon.

I ask you kindly to help me in a simple problem (for you kkk), but that is bothering me.

I have a fixed matrix (values are taken from a txt)

need a return function another matrix where a value passed per parameter is equal to the value of the second column of the matrix.

function retornaBusca(palavra, matriz){
    let result
    for (i = 0; i < matriz.lenth; i++){
        if( matriz[i][1] == palavra ){
            result.push(matriz[i][0] +'#'+matriz[i][1]
        }
    }
    return result
}

Ex:

matriz[0][1] = ['josé']        
matriz[1][1] = ['pedro']  
matriz[2][1] = ['joão']  
matriz[3][1] = ['josé']  

if I called

mat = retornaBusca('josé', matriz)

I hoped you’d return

mat[0] = 123#josé
mat[1] = 456#josé

Thank you very much

  • Where is let result do let result = []; and where is result.push(matriz[i][0] +'#'+matriz[i][1] do result.push(matriz[i][0] +'#'+matriz[i][1]);

1 answer

0

Gentlemen, I’ve discovered a patch to solve my problem.

the problem was in a specific line.

if( matriz[i][1] == palavra )

this condition never returned true, even when the values corresponded. my patch was to give a Kidney() in both.

if( matriz[i][1].trim() == palavra.trim() )

Obs. before arriving at this patch, I made a console.log to see the results.

console.log( '*' + matriz[i][1] + '*' + palavra + '*')

the result was

*josé*josé*

still did not return true. I did not understand, but the tip is, in my case I had to use Trim()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.