-2

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 ]
    }
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
natyus
  • 577
  • 1
  • 4
  • 19
  • find length of array every time and then get the index+1 and save it to your variable like let len=(array.length);now its your last index of array – salik saleem Nov 22 '21 at 12:25
  • 1
    Does this answer your question? [Get the last item in an array](https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array) – Reyno Nov 22 '21 at 12:25
  • @Reyno for some reason it gives me an error when I try to use at. It does not find it – natyus Nov 22 '21 at 12:39
  • @saliksaleem what do you mean exactly? I am not sure what to do from your example sorry – natyus Nov 22 '21 at 12:39

4 Answers4

2

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
gzn
  • 185
  • 2
  • 8
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
marmeladze
  • 6,468
  • 3
  • 24
  • 45
  • already tried this approach but the same problem – natyus Nov 22 '21 at 12:39
  • then you are doing something else wrong. above code simply takes last element from array, then we made assignment. btw, you should add additional checks for production code (e.g. check if given argument is an `Array` or not ) – marmeladze Nov 22 '21 at 12:48
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);
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
0

It is fixed now the problem was the push part in my personArray it should have been like this: personArray = this.form.controls.MultiSelectBox.value

natyus
  • 577
  • 1
  • 4
  • 19