How do I count values from an array?

Asked

Viewed 275 times

0

seems to be a silly question, but how do I count the array values and show the fraction of existing positive, negative and zeros, for example: [1,3,0, -1] and returns [0.50,0.25,0.25]? I did a for and if, but still I continue with that doubt.

Thank you

  • Kd your code? post to try to improve it ;)

  • 1

    Can you explain better what you want with examples? What is the relationship between these arrays?

  • @Sergio I have a function in which I will receive x array and in it I need to count the amount of positive, negative and 0 that it has, and with that return another array with the percentage of numbers, for example, numerosX([1, 2, 0, -1]) should return [0.5, 0.25, 0.25]because there are 50% positives, 25% zeroes, and 25% negatives.

1 answer

1


Long live!

I think this is what you want:

function percentagens(arrayNumeros) {
  var countPositivos = 0,
      countNegativos = 0,
      countNeutros = 0;

  for (var i = 0; i < arrayNumeros.length; i++) { 
    if (arrayNumeros[i] > 0) {
      countPositivos++;
    } else if (numeros[i] < 0) {
      countNegativos++;
    } else {
      countNeutros++;
    }
  }

  return [(countPositivos / arrayNumeros.length),(countNegativos / arrayNumeros.length),(countNeutros / arrayNumeros.length)];
}

var numeros = [1,3,0, -1];
alert(percentagens(numeros));

Browser other questions tagged

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