Are you developing an Angular application and suddenly find yourself in need of getting the last value from a TypeScript Array or Map? If so, read on.
It's a breeze.
Getting the Last Value From an Array
Let's start by getting the last value from an array.
Suppose, for example, you have this array:
let myArray: string = ['joe', 'john', 'james', 'jane', 'judy'];
And from that array you want the last element. In this case, that's 'judy'.
Here's how you do it:
let lastElement: string = myArray.pop();
You probably haven't used the pop() method a whole lot. But it makes sense that it works for an array.
Why? Because it's the opposite of push(), which you probably have used a time or two.
The push() method adds an element to the array. The added element becomes the last element.
The pop() method grabs the last element from the array so you can do whatever you want with it.
Getting the Last Value From a Map
But what do you do if you want the last value from a Map object?
It's simple: just convert all the values to an array and once again use pop().
Let's say you have this Map object:
let map: Map<string, number> = new Map<string, number>(); map.set('john', 14); map.set('judy', 15); map.set('james', 16); map.set('jane', 17);
And from that you want just the last value. In this case, that's 17.
Here's how you make it happen:
let lastValue: number = Array.from(map.values()).pop();
So here's what's going on in that code:
It's using Array.from() to convert all the values in the Map object That conversion will return an array that looks like this:
[14, 15, 16, 17]
Then, the code applies the quite familiar pop() method to that array.
The end result: 17.
Keep in mind, though, that Map objects order entries based on insertion order. So the last value in the map is the last value added.
In fact, that's what you see in the code above. The code added the value of 17 (associated with 'jane') last. That's why it was also the last item in the array created by Array.from().
So insertion order matters with Map objects.
Wrapping It Up
It's pretty straightforward. Feel free to apply what you've learned here to your own TypeScript code.
But, as always, just make sure you have fun!
Photo by from