How to remove items from an array?

Asked

Viewed 169 times

1

    function converterBinario () {
       numero = document.getElementById("Valor-decimal").value;
       var vetor = [];
       var i =numero;
       var cont=0;
       while(i>0){

         var resto = Math.floor(numero % 2);

         if (resto == 0 | 1 ){
            vetor[i] = resto;
            console.log(resto);
         }

        numero= Math.floor(numero/2);
        console.log(numero);
        i--;
    }

document.getElementById("resultado").innerHTML =vetor;
console.log(vetor);

}

I want to remove the zeros from the array that appear before 1.

  • It could be clearer in your question, an example of how the array is and how it should be

  • Want to take all zeros out of the array?

  • Take out all before the first 1.The array is 0,0,0,1,0,1.I want to leave 101.

1 answer

1


Can use filter():

vetor = vetor.filter(function(v,i){
   return i >= vetor.indexOf(1);
});

The i >= vetor.indexOf(1) will return only the indexes from the first occurrence of 1 in the vector.

Example:

function converterBinario () {
   //       numero = document.getElementById("Valor-decimal").value;
   numero = 10;
   var vetor = [];
   var i =numero;
   var cont=0;
   while(i>=0){
   
      var resto = Math.floor(numero % 2);
   
      if (resto == 0 | 1){
         vetor[i] = resto;
      }
   
      numero= Math.floor(numero/2);
      //        console.log(numero);
      i--;
      
     
   }

   console.log("vetor original => ",vetor.join());

   vetor = vetor.filter(function(v,i){
      return i >= vetor.indexOf(1);
   });
   
   //document.getElementById("resultado").innerHTML =vetor;
   console.log("vetor filtrado => ",vetor.join());

}

converterBinario();

  • I didn’t understand how (Return i >= vector.indexof(1);)

  • The function has 2 parameters: v and i. "v" is the value and "i" is the index. The filter will go through the array returning something. The index always finds the first occurrence, so Return will only return items of the array whose index is equal to or greater than the position of the first item of value 1 within the array.

  • 1

    In addition, the filter will only return the values where i >= vetor.indexOf(1) for true.

Browser other questions tagged

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