How to return the last record of an array with Javascript or jQuery?

Asked

Viewed 34,006 times

7

I’m making a custom search filter where the user can select the brand and product features and I return their id.

But I wanted to return only the last record of mine arrays where they contain all the information I need.

I just need to return the last record presented in the console as in the image below. Ex: mark=25,30,53 and feature:10:35:4

Follows the code:

<a href="#" class="filter-link">
  <div class="label_check">
       <input type="checkbox" id="marca-4" class="filter-check" data-tipo="marca?4" value="4">
       <div class="filter-pretty-check"></div>
       <span class="filter-desc">Nokia</span>
  </div>
</a>

    $('#filtrar-opcoes').on('click',function(){                    
                var tipos = [];
                var caracteristicas = [];
                $.each(($("input[type=checkbox]:checked")),function(index, obj){                                                
                    var $tipo =  $(obj).attr('data-tipo');                                                                                   
                    if($tipo.split('?')[0] == 'marca'){
                        tipos.push($tipo.split('?')[1]);                                    
                        var firstPartUrl = $tipo.split('?')[0] + '=' + tipos.join();                                                                
                        console.log(firstPartUrl);                                                                                                                    
                    }
                    if($tipo.split('?')[0] == 'caracteristica'){
                        caracteristicas.push($tipo.split('?')[1]);                            
                        var lastPartUrl = $tipo.split('?')[0] + '=' + caracteristicas.join(':');
                        console.log(lastPartUrl);                            
                    }
                });
            });

inserir a descrição da imagem aqui

  • 1

    Very confusing your code. Could you post the html structure ? Mainly with the attributes data-tipo ?

  • @Dontvotemedown already added a piece of the html structure

  • @Gabrielschmidtcordeiro the two answers below don’t work for you?

  • @Jéfersonbueno no cara. I just need to return the last record presented on the console as in the image above. Ex: brand=25,30,53 and feature:10:35:4

  • Then edit your question and explain what your problem is and what you’re trying to do. If you read the title of your question you will see that the two answers do exactly what is said there.

5 answers

20


You can do this using pure javascript, this way:

var array = [1, 2, 3, 4, 5];
var ultimo = array[array.length - 1];
document.write(ultimo);

If you prefer to use jQuery, you can do something like:

var array = [1, 2, 3, 4];
var ultimo = $(array).get(-1);
document.write(ultimo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • 3

    I prefer your answer. So you do not remove the last element of array if you wanted to reuse it in something else. + 1

9

Another way to get the last element of array, whereas it does not remove the last element of the array, would be using the function slice pointing to the last element through the -1.

a = [1, 2, 3]
document.write(a.slice(-1)[0])

slice return the last element of array within a array. That’s why we use the index 0.

Behold:

a.slice(-1); // Imprime: [3]
  • I edited the question. If it wasn’t recommended, I wouldn’t be posting it here :). It’s a solution and it’s done!

5

Another way would also be using the function pop. It removes the last element of the vector and returns it. I don’t know if it would be recommended in your case.

See working here.

var vetor1 = new Array(1, 2, 3, 2, 7);
var ultimo = vetor1.pop();
document.write(ultimo);

  • Remembering that pop removes the last element of array, and that’s not good in case he wanted to reuse the array.

  • @Wallacemaxters yes I put in the answer as another way and pop working.

  • Maybe just copy the array before :)

3

If it is something recurring in the project, you can extend the Array by implementing a method for it:

Array.prototype.get = function(index) {
    return this[index < 0 ? this.length + index : index];
};

So, anywhere, to search for the last element just do:

arr.get(-1)

It applies the same logic described in LINQ, but in a way global, no need to repeat the code whenever you access the last element.

See working:

Array.prototype.get = function(index) {
    return this[index < 0 ? this.length + index : index];
};

Array.prototype.last = function(index) {
    return this.get(-1);
};

Array.prototype.first = function(index) {
    return this[0];
};

const arr = [1, 2, 3];

console.log('Último elemento com get:', arr.get(-1));
console.log('Último elemento com last:', arr.last());
console.log('Primeiro elemento com first:', arr.first());

-1

Hello!

I did it this way:

//Coloque a última fruta da array em uma variável, sem remover a mesma do array

var frutas = ['Banana','Maçã','Pera','Uva','Melancia']

//Varredura para achar o último item do array (frutas.length - 1)

for (var item = 0; item < frutas.length; item++) {
    if (frutas[item] === frutas[frutas.length - 1]) {
        var ultimaFruta = frutas[item]
        console.log(ultimaFruta)
    }
}

Browser other questions tagged

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