check if item in a map is last item in javascript

To check if an item in a Map is the last item, you can use the entries() method to get an iterator of all key-value pairs in the Map, then use the next() method to iterate over the items while keeping track of the current item and checking if it is the last item.

Here's an example code snippet:

index.tsx
const myMap = new Map([['a',1],['b',2],['c',3]]);
const entries = myMap.entries();
let current = entries.next();

while(!current.done){
  const [key, value] = current.value;
  
  if(current.done){
    console.log(`${key}:${value} is the last item in the Map`);
  }
  
  current = entries.next();
}
298 chars
14 lines

In this example, we create a Map with three key-value pairs. We then get an iterator of all entries in the Map and initialize the current variable to the first item in the iterator. We then loop through each item in the Map using next() to get the next item until we reach the end of the iterator. Inside the loop, we destructure the current key-value pair into key and value variables. Finally, we check if we've reached the last item and log a message if so.

gistlibby LogSnag