Remove empty fields from an array

Asked

Viewed 883 times

0

    for(var j =0; j<data.length; j++){
        var valorEmBranco = 0;
        for(var i =0; i<data[j].length; i++){
            var porcentagem = 0;
            var valorPorColuna = data[j][i].valor;
            //alert(valorPorColuna);
            if(data[j][i].nome ===""){
                valorEmBranco += data[j][i].valor;
            } else {
                porcentagem = (valorPorColuna / (totalDados-valorEmBranco)) * 100;
            }
            data[j][i]['porcentagem'] = porcentagem;

        }
    }

https://jsfiddle.net/zm45Lywo/4/

I’m having trouble calculating percentages. I need to "sift" the blank names and remove them from the total value to make the percentage calculation. Let’s say I have 4253 elements in total, I need to subtract from this value every time the name equals empty ("); that is, (4253-numbersEmBranco), which in this case is 12 (by jsfiddle)

my multidimensional array:

    var data = [[{
        "nome": "SIM",
        "valor": 364
    },{
        "nome": "NÃO",
        "valor": 3877
    },{
        "nome": "",
        "valor": 12
    }]];


   porcentagem = (valorPorColuna / (totalDados-valorEmBranco)) * 100;

The calculation is not working. by the rule of 3, the correct for names with "NO" = 91,41% and is giving 91,16%.

  • I didn’t understand, if the value of the name field is empty it is not to consider even if in this index has a value ?

  • should be disregarded the empty (or blank) values (names). That is, in total I have 4253 elements, I must disregard the blank names. 4253-12 = 4241. Oh, I make the rule of 3 for the percentage. (it didn’t work)

2 answers

1

Hello, if I got your problem right, you can do the following by JS:

Pass the result through a test regular expression, and ignore the ones that give false Ex.:

var patt = /^([a-zA-Z])/g
if(patt.test(nome)) { //-- se virem em branco ou qualquer coisa q não seja alfabético retorna false
   //-- seu codigo
}

Ps.: You can simplify a little your be using

$(data).each(function(){
   /* this é o elemento único dentro do each */
   //this.nome
   //this.valor
})

0

Separating by steps could be like this:

// fazer uma array simples, não multidimensional
var flat = data.reduce(function(arr, _arr) {
    return arr.concat(_arr);
}, []);

// limpar os votos vazios
var limpa = flat.filter(function(el) {
    return el.nome;
});

// contar o numero máximo
var total = limpa.reduce(function(tot, el) {
    return tot + el.valor;
}, 0);

// calcular percentagens
var percentagens = limpa.map(function(voto) {
    return {
        nome: voto.nome,
        percentagem: voto.valor * 100 / total + '%'
    };
});

jsFiddle: https://jsfiddle.net/ebxdbvrf/

Browser other questions tagged

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