Tamas Hegedus Tamas Hegedus - 1 month ago 9
Javascript Question

Get last value inserted into a Set

The MDN documentation for Set says that JavaScript

Set
objects retain insertion order of elements:


Set objects are collections of values, you can iterate its elements in insertion order.


Is there a way to get the last item inserted into a
Set
object?

var s = new Set();
s.add("Alpha");
s.add("Zeta");
s.add("Beta");

console.log(getLastItem(s)); // prints "Beta"

Answer

I was not able to find any method to get last value inserted in set from ECMA 2015 Specification, may be they never intended such a method, but you can do something like:

var a = new Set([1, 2, 3]);
a.add(10);
var lastValue = Array.from(a).pop();

Edit:

on second thought, a space efficient solution might be:

function getLastValue(set){
  var value;
  for(value of set);
  return value;
}

var a = new Set([1, 2, 3]);
a.add(10);
console.log('last value: ', getLastValue(a));
Comments