2

I have a function which job is to get a total from values from an array, however it doesn't work. EG. my array looks like

    [["10", "", ""], ["10", "", ""], ["10", "", ""]]

So the value i am expecting is 30 however i am getting 0101010 in console.log

function createAv(results){
    var av = results;

    var a1 = 0;
    var a2 = 0;
    var a3 = 0;

    function percentage(av){
    var n1 = 0;
    for (var index = 0; index < av.length; index++) {

            n1 += av[index][0];
        a1 = (av[0][0] / n1) * 100; 
        a2 = (av[1][0] / n1) * 100; 
        a3 = (av[2][0] / n1) * 100; 
    }
      return n1;
    }

    var test = (percentage(av));

    return test;

  }
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
kishan patel
  • 985
  • 2
  • 10
  • 14

4 Answers4

3

The values in your array are strings, so JavaScript is concatenating them. Try using parseInt() to change the array values to numbers.

Here's a jsFiddle that illustrates how to do this.

Josh Earl
  • 18,151
  • 15
  • 62
  • 91
3

Your array of values are strings, try converting them into integers like so.

n1 += Integer.parseInt( av[index][0]);

or change your array like so

[[10, 0, 0], [10, 0, 0], [10, 0, 0]]

Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
1

It's because the numbers are in strings. You can add strings to other strings (and even add numerical values to those strings), but you'll end up with a concatenated string.

If they need to be strings, that's OK - you can use parseInt() to treat them like numbers.

for (var index = 0; index < av.length; index++) {

    n1 += parseInt(av[index][0], 10);

    a1 = (parseInt(av[0][0], 10) / n1) * 100; 
    a2 = (parseInt(av[1][0], 10) / n1) * 100; 
    a3 = (parseInt(av[2][0], 10) / n1) * 100; 
}
hugomg
  • 68,213
  • 24
  • 160
  • 246
Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
  • 1
    I need them to be all integers really because i will be doing mathematical operations on them. Could i use parseInt to convert the array into an integer array? – kishan patel Mar 08 '12 at 18:12
  • 1
    @kishanpatel: `av = av.map( function(v,i) { return v.map(Number); });` –  Mar 08 '12 at 18:35
  • 1
    Don't forget to add a base parameter to parseInt: `parseInt(str, 10) `. Otherwise if bugs out on things with leading zeroes, things like "09" – hugomg Mar 08 '12 at 18:38
  • @missingno that's an excellent point, and considering that the "numbers" here are strings, unintentional leading zeros are a definite risk. Good call. – Surreal Dreams Mar 08 '12 at 19:17
1

You can try casting it as a int

n1 += parseInt(av[index][0]);
Manatok
  • 5,506
  • 3
  • 23
  • 32