How to remove the position of an array with jquery

Asked

Viewed 2,040 times

2

I am trying to remove a position from the array with Slice, so I can only take it with the position of this array, could I take it for value? Because the position of the array changes a lot in each situation, I’m trying this way:

if($j('#folog_manha').css('display') == "none"){
   var retornox = retorno.slice('Manhã');
}

If there is no way, how would I take the positions of this array to compare? in case I take the position that is 'Morning' and give it a chance.

2 answers

4

Try to do as in this example:

var arr        = ['a', 'b', 'c', 'd', 'e']; //Array inicial
var removeItem = 'c';   // Valor do array que será removido

arr = jQuery.grep(arr, function(value) {
    return value != removeItem;
});
console.log('Array após a remoção: ' + arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Your code would look like this:

if($j('#folog_manha').css('display') == "none"){
   var removeItem = 'Manhã';

   retorno= jQuery.grep(retorno, function(value) {
    return value != removeItem;
   });

   // new array
   // fica sem "manha"

}

The method grep jQuery scrolls through all indexes of an array and returns those you want.

Reference link

  • I asked the question I would like to take for the value of it, not for the position as it changes dynamically depending on the situation, Morning can be 1, 2, 3, 4 etc..

  • but young he’s taking it for the item. in case there moves to 4 he takes the 4

  • That would be his key, I’d have to know his position, so I’d have to file a request for each situation, the value would be simpler because it never changes. (2) ["Comercial", "Manhã"]&#xA;0&#xA;:&#xA;"Comercial"&#xA;1&#xA;:&#xA;"Manhã"&#xA;length&#xA;:&#xA;2&#xA;__proto__&#xA;:&#xA;Array(0)

  • Now that I saw that it is another function, I thought it was the Slice, because I tried to pass the value and it didn’t work, I can test yours, but the 13dev already worked for me

  • yes @Gustavosouza no problem. although I answered first, and did in jquery that was what tagged in the tag.

  • Yes, but his was more practical, with splice I can remove directly from the original array, so I can do several checks without putting in supporting variables, because I will have to do some 6 checks of this.

Show 1 more comment

3


To remove a position from an array by the value just use the Index in the way splice

var arr = [ "abc", "def", "ghi" ];

arr.splice(arr.indexOf("def"), 1);
  • 1

    It worked as it should, simple and practical, thank you.

  • You’re welcome! I’m grateful to have helped

Browser other questions tagged

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