Check the amount of negative elements in a JS array

Asked

Viewed 3,418 times

4

I am initiating Javascript studies and I come across a question where I need to identify negative elements in an array and return the amount of these numbers. Remembering that there may be empty, mixed (+ and - ) negative and positive arrays.

I tried to do with this one, but it’s not working:

   function quantidadeDeMesesComPerda(umPeriodo){
  let quantidade =0;
  let somaDeElementosNeg = 0;
  let somaDeElementosPosit=0;
  let elementos =0;
  for(var i = 0; i < umPeriodo.length; i++){  
    elementos = umPeriodo[i];
    somaDeElementosNeg+=i;
    somaDeElementosPosit-=i;
        if(elementos < 0){
          quantidade = somaDeElementosNeg;
            return quantidade.length;
      } else if(elementos >0){
        quantidade = somaDeElementosPosit;
            return quantidade.length - somaDeElementosNeg.length;;
      } else {
        return 0;
      }   
  } 
}
  • You can give an example of the type of arrays that passes to the function?

  • 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.

5 answers

9


What you need is:

function quantidadeDeMesesComPerda(umPeriodo) {
  return umPeriodo.filter(nr => nr < 0).length;
}

const test = quantidadeDeMesesComPerda([10, -10, 2, 100]);
console.log(test);

That is, with the .filter go through the array and delete all positive or zero numbers. At the end return .length You’ll find out how many left unpopulated.

The code you have had several problems... for example:

  • somaDeElementosNeg += i;

    here you are adding in each count of i which makes no sense because a Plan[i] may be positive or negative

  • return quantidade.length;

    a number does not have .length, what you want is the very "quantity" without .length
    another problem is the return it will cancel the "for loop" and give you reply before analyzing all elements...

If you want to do it with a for, using an incremental variable you can do so:

function quantidadeDeMesesComPerda(umPeriodo) {
  let perdas = 0;
  for (let i = 0, l = umPeriodo.length; i < l; i++) {
    if (umPeriodo[i] < 0) perdas++;
  }
  return perdas;
}

const test = quantidadeDeMesesComPerda([10, -10, 2, 100]);
console.log(test);

3

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.

  • 1

    there is some way to solve we use only For and If ?

  • Yes @Stéphanieverissimo, right now I’m closing the office, but when I get home I write the solution with if and for. OK?

  • OK, I’ll be waiting. VLW

  • I ended up doing, I will put now, when I get home I put an explanatory ceiling.

  • 1

    How fast, I’ve been almost 2 days trying to solve this exercise

  • I already edited the answer is the first example. Now I went!

Show 1 more comment

2

A simple way to do this would be like this, using the foreach. It’s as simple as it is, I think it would take you 10 minutes to study your structure.

function verifyArray(arr) {
    let elemNegative = 0, elemPositive = 0
    arr.forEach((element) => (element > 0 ? elemPositive++ : elemNegative++))	
    return `Foram encontrados [${elemPositive}] positivo(s) e [${elemNegative}] negativo(s)`
}

console.log(verifyArray([1,2,3,4,5,-5,-6]))

  • I’ve researched videos and Google about foreach, but since I’m practically a layperson at all and I’m learning by myself, it’s a little hard to understand at first. You know if there is any resolution just with for and if?

1

function quantidadeDeMesesComPerda(umPeriodo){
   let quantidade = 0;

   for( let i=0;i<umPeriodo.length;i++){
       if(umPeriodo[i]<0){
          quantidade = quantidade + 1
    }
    }
           return quantidade;
    }
  • I think that’s what you were looking for...

  • Improve this understanding and explain to the user that this code is different from the answer code accepted.

1

// Loop "FOR" to check an array that contains negative and positive numbers and display them. // Example 1:

let listaDeGanhos = [10, 30, -10, -5, 40, 8, -2, -10, -15]
let totalNegativos = 0
let totalPositivos = 0 

for(i = 0; i < listaDeGanhos.length; i++) {
    if(listaDeGanhos[i] < totalNegativos) {
        totalNegativos++ // incrementa os numeros negativos do array
    } else {
        listaDeGanhos[i] > totalPositivos
        totalPositivos++
    }
}
                                                
if(totalNegativos === totalPositivos) {
        console.log(totalNegativos + " Mes Negativos", totalPositivos + " Mes Positivos")  
    }else if(totalNegativos > totalPositivos) {
        console.log(totalNegativos + " Mes Negativos")
    }else {
        console.log(totalPositivos + " Mes Positivos")
}

Browser other questions tagged

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