Javascript function using For

Asked

Viewed 68 times

-4

I have an array with the height of several students and need to sort in groups by height. I do a for to scan the array and inside the for a conditional if to know if the student enters that group, and then I fill the group array.

The problem is that the array is filling with spaces null and I don’t know if the mistake is in if.

var alunos = [170, 159, 151, 187, 156,]

function qualGrupo(alunos) {

    for (var i = 0; i < alunos.length; i++) {
        if (alunos[i] >= 150 && alunos[i] <= 159) {
            grupoA[i] = alunos[i]
        }
    }
}

The return is like this: Your groupA array has these values:

[,159,151,,156]

I don’t want you to have these blank spaces. How do you do?

  • Where does this variable come from grupoA? You only need to check in with students who are 150 and 159?

  • possible duplicate https://answall.com/questions/461226/fun%C3%A7%C3%a3o-javascript-create-arrays-from-another-array

  • that 154 on the return fell from the sky?

  • Use grupoA.push(alunos[i]) instead of grupoA[i] = alunos[i]

  • Leo Letto grupoA was the variable created, and the control would be just that.

  • Leo Caracciolo, had more numbers in the student array I forgot to put. about the duplicate had not found before. Thanks

  • Rafael Tavares will try it. Thank you

Show 2 more comments

2 answers

2

Hello, from what I understand, you want the end to stay [159,151,156,154]. If so, change your

grupoA[i] = alunos[i]

for

grupoA.push(alunos[i])

Must solve.

0


That question is similar to that here which was closed and resolved by the comments

  var alunos = [170, 159, 151, 187, 156,]; 
   
   var grupoA = [];
 
    for (var i=0; i<alunos.length; i++){
 
        if(alunos[i]>150 && alunos[i]<=159){
             grupoA.push(alunos[i]);
        }
 
    }
 
       console.log(grupoA.join());
       console.log(grupoA);

But if you prefer another way

var alunos = [170, 159, 151, 187, 156,]
var grupoA = [];
function qualGrupo(alunos) {

    for (var i = 0; i < alunos.length; i++) {
        if (alunos[i] >= 150 && alunos[i] <= 159) {
            grupoA += alunos[i]+",";
        }
    }
    grupoA = grupoA.substring(0,(grupoA.length - 1));
}
qualGrupo(alunos);

console.log(grupoA);

Browser other questions tagged

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