javascript – I have to know how many times an element is repeated

Question:

function cuantosRepetidos(array, elemento) {

The function called how cuantosRepetidos receives as arguments: an Array of Array's called array and a string called elemento

Each subarray contains string's .

It must return the number of times that elemento is repeated within the subarrays. For example, the call:

cuantosRepetidos([['manzana', 'naranja'],['sandia', 'pera'],['uva', 'manzana']], 'manzana')

It should return 2, since 'apple' is repeated 2 times. Note: You can use for nested loops.

 function cuantosRepetidos(array, elemento){ var contador = 0; for (var i = 0; i < array.length; i++) { for(item of array[i]){ if(item === elemento) { contador++; } // fin if } // fin for } // fin for } // fin function return contador; // ??? } // ??? cuantosRepetidos([['manzana', 'naranja'],['sandia', 'pera'],['uva', 'manzana']], 'manzana');

This is what I did but when I went through a test it gave me an error.

Answer:

You are committing the cardinal sin of not indenting the code.

The code is indented, not to help the computer, which processes it however it is, as long as the syntax is valid.

The code is indented to help yourself , as it is much easier to understand, in addition to being able to appreciate much more quickly a mistake as basic as the one you are making:

Your code has an extra closing brace.

By correcting that detail , in addition to indentation correctly, we obtain:

 function cuantosRepetidos(array, elemento) { var contador = 0; for (var i = 0; i < array.length; i++) { for(item of array[i]) { if(item === elemento) { contador++; } } } return contador; } console.log('Repetidos: ' + cuantosRepetidos([['manzana', 'naranja'],['sandia', 'pera'],['uva', 'manzana']], 'manzana'));

As you can see, I have added an output to the console to directly see the result, which you can execute directly in the browser (with the execute button above).

Scroll to Top