skip to Main Content

I found some answers suggesting iterating through the Map, setting the iterated element to a variable and then reading it after the iteration. But isn’t there any better, more elegant view? I could not find a better solution so far.

7

Answers


  1. Convert the Map to an array using the Array.from() method and then use the array index to access the last item.

    // Convert Map to an array and get the last item
    const myArray = Array.from(myMap);
    const lastItem = myArray[myArray.length - 1];
    
    // Log the last item to the console
    console.log(lastItem);
    

    you can get the last item by accessing the array index [myArray.length - 1]

    Login or Signup to reply.
  2. You can convert the Map to an array of entries, then get the last element.

    const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
    let lastEntry = [...map].at(-1);
    console.log(lastEntry);
    
    // or only get last key/value
    let lastKey = [...map.keys()].at(-1);
    let lastValue = [...map.values()].at(-1);
    console.log(lastKey, lastValue);

    However, it’s more efficient to just iterate over the entries and keep the last one.

    const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
    let entry; for (entry of map);
    console.log(entry);
    Login or Signup to reply.
  3. With the built-in Map there’s no way other than iterating the entries and return what comes last. You can, however, extend Map so that it can record its own "history", for example:

    class MapWithHistory extends Map {
        history = []
    
        set(key, val) {
            this.history.push(key)
            return super.set(key, val)
        }
    }
    
    m = new MapWithHistory()
    
    m.set('foo', 123)
    m.set('bar', 456)
    m.set('baz', 789)
    
    lastKey = m.history.at(-1)
    
    console.log(lastKey)
    Login or Signup to reply.
  4. const inputMap = new Map([
      ['k1', 'v1'],
      ['k2', 'v2'],
      ['k3', 'v3']
    ]);
    
    const lastEntry = [...inputMap.entries()].pop();
    console.log(lastEntry); 
    Login or Signup to reply.
  5. convert a map to the array with spread operator and use .pop

    const inputMap = new Map([
      ['k1', 'v1'],
      ['k2', 'v2'],
      ['k3', 'v3']
    ]);
    
    const lastEntry = [...inputMap].pop();
    console.log(lastEntry); 
    Login or Signup to reply.
  6. No, there is not. Maps are not an ordered data structure in the sense that they support indexed access – all they have is a deterministic iteration order. If you care about controlling the order of elements or accessing them by index, use an array (possibly in addition to the map).

    In terms of elegance, I would recommend a helper function that takes an iterator:

    function last(iterator) {
      let element;
      for (element of iterator) {}
      return element;
    }
    

    then call it as

    last(map.values())
    

    or

    last(map.entries())
    
    Login or Signup to reply.
  7. You could iterate the map directly and use a counter from size and get the last pair.

    const
        map = new Map([['k1', 'v1'], ['k2', 'v2'], ['k3', 'v3'], ['k4', 'v4']]),
        last = [];
    
    let s = map.size;
    map.forEach((k, v) => {
        if (!--s) last.push(k, v);
    });
    
    console.log(last);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search