Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

285
Visualizações
How to get the last element of array and save in variable

I am trying to save the last element of an array which gets its values from a multiselect dropdown and looks like this for example with two elements: [34, 33]

What I want to do know is to always get the last element inside it in this case the 33 and save it for further use in a variable. But for some reason personId2 is always all elements like this: [34, 33] But I want to have just the 34 if it is the only element or the 33 if it is the last element .

this is the part where I am trying to get the last element:

let personId = 0
    let personersonId2 = 0
    this.personArray.push(this.form.controls.multiSelectBox.value)
    this.personArrayStaging = this.personArray[length]
   
    for(personId = 0; personId < this.personArray.length - 1; personId ++){
        personId2 = this.personArray[personId ]
    }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Can not follow the code, but if you want to grab the last element of an array all you need is calling arr[arr.length-1]. If you don't want to repeat it over and over, make it a function

lastElement = (arr) => arr[arr.length-1]


let x = lastElement([]) // x = undefined
let y = lastElement([1,2]) // y = 2 
let z = lastElement([3]) // z = 3
about 4 years ago · Juan Pablo Isaza Relatório

0

In order to get the last element of the array, the simplest solution is to call arr.at(-1)

const arr = [11, 22, 33, 44];
const lastElement = arr.at(-1); // 44
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use length-1or the javascript function pop(). Importnat note: But pop will remove the last element from your array.

let arr = ['hello','world'];
const last = arr.pop();
console.log(last);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda