Using for of.
function quantidadeDeMesesComPerda(umPeriodo){
var contador = 0;
for(var item of umPeriodo) {
if (item < 0) contador ++;
}
return contador;
}
console.log("Meses com perda: " + quantidadeDeMesesComPerda([-1,5,3,8,5,-5,-6,-10]));
Can be done with iteration loop for...of
. The noose for...of
traverses iterative objects (including Array, Map, Set, the Arguments object and so on), calling block statements to be executed for the value of each distinct object.
In the example I started the contador
at zero and used for of
to scroll through each item in the array umPeriodo
, for each item check if it was a negative, if it was a negative I added one to the counter, otherwise it would go to another element. In the end I only returned the value of this counter.
Syntax
for (variavel of iteravel) {
declarações
}
variable
At each iteration, a value different from iteravel
is assigned to the variable.
iterable
Object whose attributes will be iterated.
Using reduce.
function quantidadeDeMesesComPerda(umPeriodo){
return umPeriodo.reduce((acumulador, valorAtual )=>{
return (valorAtual < 0)? acumulador + 1 : acumulador;
}, 0);
}
console.log("Meses com perda: " + quantidadeDeMesesComPerda([-1,5,3,8,5,-5,-6,-10]));
Can be done with Array.reduce()
. The method reduce()
performs a reducer function provided by you for each member of the array, adding or decreasing the accumulator, or applying complex operations, according to your needs.
In the example I started the accumulator at zero and each negative value found I returned 'accumulator + 1' or only acumulador
if the value was a positive or if it was not a number and this value is automatically passed by reduce()
for next iteration.
Syntax
array.reduce(callback[, valorInicial])
callback
Function that is executed on each value in the array, takes four arguments:
initial value
Optional. Object to be used as the first argument of the first callback function call. Calling reduce() in an empty array with no initial value is an error.
The callback parameters are:
Accumulator
The value returned in the last callback invocation, or the Initial Value argument, if
provided. (example below).
valorAtual
The current element being processed in the array.
Indice
The index of the current element being processed in the array.
array
The array to which the reduce() function was called.
You can give an example of the type of arrays that passes to the function?
– Sergio
yes, one of the examples that fit this solution is: [10,-10,2,100] it should return 1, but with my code does not work.
– Stéphanie Verissimo