Knowing what index of array values matches variable

2

I have two JSON arrays in JavaScript and both are like this.

First array:

[""Amarelo"", ""Amarelo"", ""Amarelo"", ""Preto"", ""Preto"", ""Preto""]

Second array:

[""Pequeno"", ""Médio"", ""Grande"", ""Pequeno"", ""Médio"", ""Grande""]

And I can have two variables that change by click which can be, for example "yellow" and "medium."

The question is: how do I know the index of when the values of the variables match those of the arrays?

Looking at this I know that the match index is 1, but how do I get JavaScript to figure this out on its own?

With this index value discovered I'll be able to call the rest of the content dynamically.

Can anyone suggest a north for me?

    
asked by anonymous 21.06.2018 / 19:42

4 answers

1

If the two arrays always have the same size, loop with a counter based on one of them, and check the value of the two. For example:

var cores = ["Amarelo", "Amarelo", "Amarelo", "Preto", "Preto", "Preto"];
var tamanhos = ["Pequeno", "Médio", "Grande", "Pequeno", "Médio", "Grande"];

var corEsperada = 'Amarelo';
var tamanhoEsperado = 'Médio';

for(var i=0; i<cores.length; i++) {
    if(cores[i] === corEsperada && tamanhos[i] === tamanhoEsperado) {
        alert('Encontrado o par ' + corEsperada + '/' + tamanhoEsperado + ' na posição ' + i);
    }
}
    
21.06.2018 / 20:16
0

You can use the indexOf() function. In your case it would look like this:

var array1 = ["Amarelo", "Amarelo", "Amarelo", "Preto", "Preto", "Preto"];
var variavel1 = "Amarelo";
var index1 = array1.indexOf(variavel1);

index1 will be the value of the first element equal to "Yellow", 1 in the case. If it does not find it, it returns -1.

    
21.06.2018 / 19:58
0

Proposal:

var cores = [ 'amarelo', 'amarelo', 'preto', 'azul' ];
var corProcurada = 'preto';
var indice;

alert((indice = cores.indexOf(corProcurada)) > -1 ? indice + 1 : 'nao achei'); // 3

Source: here

    
21.06.2018 / 19:55
0

Another solution in ES6 would be to use the .some() . So you break the loop as soon as the condition is satisfied:

  

The method some () tests if some of the elements in the array pass the test implemented by the assigned function.

const cores = ['Amarelo', 'Amarelo', 'Amarelo', 'Preto', 'Preto', 'Preto']
const tamanhos = ['Pequeno', 'Médio', 'Grande', 'Pequeno', 'Médio', 'Grande']

const corUsuario = (corUsr) => corUsr === 'Preto'
const tamUsuario = (tamUsr) => tamUsr === 'Grande'

cores.some((cor, i) => {
  if (corUsuario(cor) && tamUsuario(tamanhos[i])) {
    console.log('produto disponivel: cor ${cor}, tamanho ${tamanhos[i]} no índice ${i}')
  }
})
    
22.06.2018 / 05:23